Reputation: 26168
I'm just curious and was wondering if there is a "good practice" answer to the following:
If I have a lightweight NSManagedObject subclass in Core Data in which objects will be created and deleted quite frequently and the subclass itself is fairly straightforward (e.g., one relationship, minimal attributes), is it advisable to create and delete instances as needed or to set and unset existing instances as appropriate?
E.g., let's say we have a theoretical NSManagedObject subclass called Tag
that has a relationship to another subclass MyObject
. MyObject
can have many Tag
objects but each Tag
has at most one MyObject
object. Tag
has one attribute, text
, which is an NSString set by the user.
In the above case, I can think of two different implementations:
Tag
, you create a new Tag
. When you want to remove a Tag
, you delete it from Core Data.Tag
, you first search for existing Tag
objects with text = nil
and only create a new Tag
object if all existing Tag
objects are used. When you want to remove a Tag
, you remove its relationship to its MyObject
object and set text = nil
."Create & Destroy" seems more straightforward and takes up exactly as much space as it needs, but "Update & Reuse" minimizes the number of times you delete and create objects. (I would imagine deleting spare Tag
objects on a save
and also keeping track of unset Tag
objects so that you don't have to fetch from Core Data every time.)
Which implementation would you recommend? Is there a different implementation that I haven't thought of? Am I asking the wrong questions / not providing enough details?
I suppose I could make a sample Xcode project and test this out myself, but I'm guessing that you will have a more informed opinion / more experience beyond simply optimizing for time and memory.
Upvotes: 1
Views: 388
Reputation: 46718
Create and destroy is the best practice. Reuse has implications when your application gets more complex and risks merge problems. The cost difference between an insert and an update is minimal.
Upvotes: 1