Avoid updating a column in Realm and Swift after the initial load has been completed

Currently, I am working on a project that involves using Realm. As part of this project, I make two calls to the backend to retrieve JSON data. The first call is used to populate my database (named Categories) with category information such as an ID, Name, and imageUrl.

class Categories: Object, Mappable {
    dynamic var id:Int = 0
    dynamic var name:String?
    dynamic var imageUrl:String?

    required convenience init?(_ map: Map) {
        self.init()
    }


    override class func primaryKey() -> String {
        return "id"
    }

    func mapping(map: Map) {
        id <- map["id"]
        name <- map["name"]
        imageUrl <- map["imageUrl"]
    }    
}

The second call returns various information and for each item, it includes a category Name and Id. This information is also stored in the "Categories" Object, however, there is no imageUrl field available in this JSON.

class Publication: Object, Mappable {
    dynamic var id: Int = 0
    ...
    var categories = List<Categories>()

    required convenience init?(_ map: Map) {
        self.init()
    }

    override static func primaryKey() -> String? {
        return "id"
    }

    func mapping(map: Map) {
        id <- map["id"]
        // map ID and Categories of this item to the Categories db
        categories <- (map["categories"], ListTransform<Categories>())
    }    
}

In some instances, the Publication JSON updates the Category database but does not include the imageUrl field as shown below:

{
    "categories": [
        {
            "id": 39,
            "name": "Etenswaren "
        },
        {
            "id": 91,
            "name": "Dranken"
        }
    ],
}

An issue I am facing in my database is that the imageUrl field in the Categories object gets cleared after these two calls are completed. The categories found in the Publication class do not contain any URLs anymore. I want to preserve the imageUrl column even after filling it, so all URLs remain intact regardless of being mentioned in Publication. How can I achieve this?

I am open to different solutions to address this problem.

https://i.stack.imgur.com/SptWn.png

Answer №1

When deserializing JSON to your object model using ObjectMapper, the property categories in Publication relies on a custom transformation called ListTransform. This transformation likely resembles something like this gist.

The ListTransform creates a new List and maps all values from the provided JSON array if it is indeed an array. If you add the resulting Publication object to Realm without explicitly setting the parameter update to true, the categories will be treated as new objects. However, setting update to true will overwrite existing fields with nil values.

To prevent this behavior, consider implementing a custom TransformType that looks up objects by their primary key in Realm.

Your unique custom TransformType code snippet here...

In your Publication class, you can use this custom transform as shown:

Your unique Publication class code snippet here...

One challenge you may encounter when solving this issue is accessing Realm within the mapping function due to constraints posed by ObjectMapper's final Swift classes. Injecting a Realm instance directly is not possible according to Dependency Injection best practices.

To work around this limitation, I suggest utilizing the default Realm configuration. However, if you have different configurations, additional steps would be required. Sharing Realm instances globally is discouraged due to thread safety concerns, so consider sharing your RealmConfiguration or implementing a factory method to generate Realm instances for each thread.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to add custom styles to an Ext JS 'tabpanel' xtype using the 'style

Is there a way to change the style of a Ext.tab.Panel element using inline CSS structure like how it's done for a xtype: button element? { xtype: "button", itemId: "imageUploadButton1", text: "Uploader", style: { background : ' ...

Is there a way to open an HTML file within the current Chrome app window?

Welcome, My goal is to create a Chrome App that serves as a replacement for the Chrome Dev Editor. Here is my current progress: background.js chrome.app.runtime.onLaunched.addListener(function() { chrome.app.window.create('backstage.html', { ...

How can I update my outdated manifest v2 code to manifest v3 for my Google Chrome Extension?

Currently, I am developing an extension and using a template from a previous YouTube video that is based on manifest v2. However, I am implementing manifest v3 in my extension. Can anyone guide me on how to update this specific piece of code? "backgro ...

What is the process of using an if statement in jQuery to verify the existence of a property in a JSON file?

I am working on a task to incorporate an if statement that checks for the existence of a specific property in a JSON file. If the property exists, I need to display its value within HTML tags <div class='titleHolder'> and "<div class=&ap ...

Why is the toggle list not functioning properly following the JSON data load?

I attempted to create a color system management, but as a beginner, I find it quite challenging! My issue is: When I load my HTML page, everything works fine. However, when I click on the "li" element to load JSON, all my toggle elements stop working!!! ...

fullcalendar adjusting color while being moved

Currently, I have implemented a fullcalendar feature that displays entries for multiple users with different colored calendars. However, there seems to be an issue when dragging an entry to another date - the color reverts back to default. Below is an exa ...

Modifying the color of a variety of distinct data points

There was a previous inquiry regarding Changing Colour of Specific Data, which can be found here: Changing colour of specific data Building upon that question, I now have a new query. After successfully changing the 2017 dates to pink, I am seeking a way ...

Is it acceptable to replicate another individual's WordPress theme and website design in order to create my own WordPress website that looks identical to theirs?

It may sound shady, but a friend of mine boasts about the security of his WordPress website, claiming it's impossible to copy someone else's layout or theme. However, my limited experience in web development tells me otherwise. I believe it is po ...

Develop a CSS layout for the specified design

Aiming to achieve a unique layout using dynamic html strings. The challenge arises when transitioning to the second page as the layout does not adjust upward and images cannot be added to the first page. Attempting to implement the following sample code ...

Utilizing Javascript to Extract Data from Twitter Json Files

Can someone provide assistance with parsing JSON feed text retrieved from Twitter? I am looking to access and apply style tags to elements like the link, created date, and other information. Any tips on how I can achieve this task successfully would be g ...

Retrieve jQuery CSS styles from a JSON database

I've been attempting to pass CSS attributes into a jQuery method using data stored in a JSON database. However, it doesn't seem to be functioning as expected. I suspect that directly inputting the path to the JSON variable may not be the correct ...

CSS background image referencing in React to the public folder's path

I am currently working on a project using Create-React-App and I am trying to set a background image for my header section. Here is how I'm attempting to do it: background-image: url('~/Screenshot_11.png'); However, I encountered an error w ...

Trouble displaying data in Jquery JSON

I've been on the hunt for hours, trying to pinpoint where the issue lies within my code. Despite scouring different resources and sites, I can't seem to figure it out. Whenever I click "Get JSON Data," nothing seems to display below. Can someone ...