Ken M. Haggerty
Ken M. Haggerty

Reputation: 26168

Fetch and update, or create and delete NSManagedObjects in Core Data?

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" 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

Answers (1)

Marcus S. Zarra
Marcus S. Zarra

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

Related Questions