4thSpace
4thSpace

Reputation: 44352

How to save an NSManagedObject?

I've created an NSManagedObject class that matches the corresponding Core Data entity. The class has an initializer so I can pass in property values and assign them.

Once the NSManagedObject class is initialized and ready to be saved to Core Data, how exactly do you save it?

The examples I've seen all start by creating a new class through NSManagedObjectContext. I don't want to go that route since I'm creating the class like any other class.

Is there some way to pass this object to NSManagedObjectContext and call its save() method.

Upvotes: 0

Views: 832

Answers (1)

Tom Harrington
Tom Harrington

Reputation: 70986

It sounds like you're probably not properly initializing your managed objects. It's not enough to assign property values in an initializer-- you have to use the designated initializer. The examples you've seen all use an NSManagedObjectContext because the designated initializer for a managed object requires one. If you don't provide one, you're not using the designated initializer, and you won't be able to save your objects in Core Data.

This is one of the base requirements of Core Data. You must use managed objects, which must be initialized properly, and doing this requires a context.

You don't save a managed object-- you tell a context to save any changes it knows about, which includes changes to any of its managed objects. You can make that more fine-grained by creating a new context that only knows about one new object. But saving an object on one context doesn't automatically let other contexts know, so you end up adding some complexity to keep changes synced.

Apple's Core Data Programming Guide covers this in detail with sample code.

Upvotes: 1

Related Questions