Matt Miller
Matt Miller

Reputation: 1431

Using Core Data to store custom objects - what am I missing here?

I have a simple custom object ("Ingredient") with instance variables, class methods, and instance methods. This custom object is inexorably entwined throughout my application. I want to store instances of this custom object using Core Data. From what I have read, having instance variables and methods in managed objects are discouraged.

So now I'm confused on how to proceed.

From examples of similar situations, it seems that it is common practice to fetch the results and put it in an array like so:

NSMutableArray *array = [managedObjectContext executeFetchRequest:fetchRequest error:&error];

But I am unclear what I can do with the mutableArray of objects. Can I do all the things I want to do currently with my custom object: modify instance variables, send the object to methods, etc?

Or do I create a "ArchivedIngredient" managed object with attributes matching my "Ingredient" instance variables, using my "Ingredient" object as I currently do - then convert "Ingredient" back to a "ArchivedIngredient" object when I need it stored? If so, how would that be done?

What am I missing here?

Upvotes: 0

Views: 321

Answers (1)

J2theC
J2theC

Reputation: 4452

From what I have read, having instance variables and methods in managed objects are discouraged.

I do not now what you mean by this, but if what you mean is that you are not supposed to create classes based on your core data entity, you are wrong. You can use the core data inspector to assign a custom class to your entity, and create the header and source file of the implementation of that class by selecting the entity on your model, and using Xcode's product menu to find "Create NSManagedObject Subclass". This will generate your NSManagedObject subclass. You can add instance method and class method, just like other classes.

When you modify a property of your custom class, and you wish to save these changes, you need to get the managed object context you used to fetch the object and call the save method. This will put the changes in the persistent store.

Also, note that the method you are calling "executeFetchRequest" does NOT return a mutable array. It returns a immutable subclass of NSArray, which you must treat as an NSArray.

Upvotes: 1

Related Questions