How to efficiently handle temporary objects in Core Data, since the variable objectID changes between temporary objects and permanent objects?

What is the best way to handle temporary objects in Core Data? I have seen solutions in which temporary contexts are created, where they are inserted into nil contexts, etc.

However, here is the problem that I see in both of these solutions. I use Core Data for my object model, and in some of my views NSSet objects of the main data are stored. The problem is when the object is stored, the identifier of the object changes, which actually invalidates anything stored in any NSSet, since isEqual and hash are now different. Although I could invalidate an object stored in NSSet, it is often impractical and, of course, not always easy.

Here is what I reviewed:

1) override the isEqual method and hash on NSManagedObject (obviously bad)

2) do not put NSManagedObject in an NSSet (use NSDictionary, where the key is always fixed)

3) use a completely different type for storage in NSSet, where I could correctly implement the isEqual and hash code methods

Does anyone have a better solution for this?

+4
source share
4 answers

However, here is the problem that I see in both of these solutions. I use Core Data for my object model, and in some of my views NSSet objects of the main data are stored. The problem is when the object is stored, the identifier of the object changes, which actually invalidates anything stored in any NSSet, since isEqual and hash are now different.

tjg184,

Your problem here is not the transition to persistent identifiers, but that your container class depends on an immutable hash. Therefore, change the container class to an array or dictionary, and this problem will disappear. (You discard uniqueness with an array, but it is easy to deal with disconnecting through a transition set to perform a unique one.)

Andrew

+1
source

ManagedObjects in NSSet - this is similar to a master data relationship. Why not just store temporary managed objects in a relationship, and Core Data takes care of the problems you are currently facing. Then you can focus on when and how to delete temporary objects, or break the connection or something else.

+3
source

Perhaps you can subclass NSManagedObject and override the willSave and didSave methods to delete, and then re-add the objects to your set.

Actually, I took a different approach - using the NIL context and providing a base class to handle insertion into the context. It works very well and is the cleanest solution I have found. The code can be found here ... Temporary master data

0
source

A possible solution would be to convert temporary identifiers to permanent using [NSManagedObjectContext obtainPermanentIDsForObjects:error:] .

But keep in mind that this can be expensive, especially if you have many objects that you need to handle in this way.

0
source

Source: https://habr.com/ru/post/1347134/


All Articles