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:
- Create & Destroy: When you need a new
Tag, you create a newTag. When you want to remove aTag, you delete it from Core Data. - Update & Reuse: When you need a new
Tag, you first search for existingTagobjects withtext = niland only create a newTagobject if all existingTagobjects are used. When you want to remove aTag, you remove its relationship to itsMyObjectobject and settext = 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.