Home > Back-end >  Is it 'bad practice' to overwrite a core data object?
Is it 'bad practice' to overwrite a core data object?

Time:01-12

I am saving some basic data for local notifications in core data, since there is no point in storing it on my remote backend. Let's say my entity is called ChatRoom, it has a unique id field and another field called "lastCheckedDate" that stores a date.

Every time a user views a chat room I want to update the lastCheckedDate field. Is it safe for me to just overwrite the old one since the id's are unique? I see no harm in this, but am also not too familiar with core data.

Ex.

func saveLastActivity(_ chatRoomID: String) {
    let coreDataChat = ChatRoom(context: container.viewContext)

    coreDataChat.id = chatRoomID
    coreDataChat.lastCheckedDate = Date()

    do {
        try container.viewContext.save()
    } catch {
        print("error saving to cd: \(error)")
    }
}

If I have a chat room with the id "0" and save it to CD for the first time, and then save another chat room with the same id "0", but this one has the updated date value, will it delete the old value and replace it with the "new"? (only the date changes)

CodePudding user response:

If you specify a mergePolicy then Core Data should be able to resolve duplicates introduced when you call save. Otherwise you should be seeing an error if you try to save a new object with a duplicate value for an attribute that has been constrained as unique. Note, this is not "bad practice"; rather it is a feature of Core Data.

e.g.

self.container.viewContext.mergePolicy = NSMergePolicy.mergeByPropertyObjectTrump

More info: https://www.hackingwithswift.com/books/ios-swiftui/ensuring-core-data-objects-are-unique-using-constraints

CodePudding user response:

It is generally not recommended to overwrite core data objects, as it can lead to conflicts with other development work. In some cases, you may need to modify a core object's behavior or structure in order to achieve the desired outcomes for your project. If this is the case, you should create a new custom object that will extend from the original and incorporate any necessary changes. This approach ensures that all of your changes are contained within one place and that any potential issues can be more easily identified and isolated.

Additionally, when a new version of the base object is released, it will be easier to update just your custom version instead of having gone through and individually overwritten each change in the original. Ultimately, if you must make modifications to a core object, it is best to take the approach of creating a new custom object than overwriting the original. This will help avoid potential conflicts and make updating and debugging easier down the line. More info: https://www.deviantart.com/mathewrosed/journal/

  • Related