12

I have an entity object Country with country name and country code. It is a subclass of NSManagedObject and I am using it with core data model to store its value to a persistent store.

I have a place where the same Country object will used as a normal object i.e. I will use it to store some temporary country name.

For that I have initialized the Country as following

[NSManagedObject alloc] init]

Initialization successfully done, but I am not able to set any property to that object. Hence I did an exploration. In that I found that, init for the NSManagedObject is not supported as per the documentation.

I don't know how to use the NSManagedObject Country with CoreData as well as a normal Object.

2 Answers 2

11

2nd paragraph of the NSManagedObject class documentation's overview:

A managed object is associated with an entity description (an instance of NSEntityDescription) that provides metadata about the object (including the name of the entity that the object represents and the names of its attributes and relationships) and with a managed object context that tracks changes to the object graph. It is important that a managed object is properly configured for use with Core Data. If you instantiate a managed object directly, you must call the designated initializer (initWithEntity:insertIntoManagedObjectContext:).

From the documentation of the method:

Important: This method is the designated initializer for NSManagedObject. You should not initialize a managed object simply by sending it init.

The documentation is actually very good.

You do not want to try to use an NSManagedObject outside of a viable CoreData stack. NSManagedObjects are quite explicitly designed to work within a correctly configured Core Data environment. If you need a temporary instance, you can either create an in-memory store or create one in your regular store and just don't save the changes without deleting it first.

2
  • Thanks!! So it is not possible to initialize as we do for a normal object. I suppose you are referring to NSInMemoryStoreType for the persistent store, so the inserted entity will be stored in volatile RAM memory. I have another question - when actually it will be cleared off or do we have to flush it out manually?
    – raksja
    Sep 2, 2009 at 12:03
  • It'll be cleared when you tell it to clear (manually) or when your app quits... InMemoryStores work just like the other stores, just that persistence is... in memory only.
    – bbum
    Sep 2, 2009 at 15:28
2

Use initWithEntity:insertIntoManagedObjectContext: and pass nil for managed object context.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.