How to associate NSManagedObject with a context after its initialization?

For example, if I have an NSManagedObject named Items , and I want to set ManagedObjectContext later (and not during initialization), how would I do it?

I am currently doing this:

 Items *item = [NSEntityDescription insertNewObjectForEntityForName:@"Items" inManagedObjectContext:_context]; 

This automatically associates it with _context .

But what if I want to do this:

 Items *item = [[Items alloc] init]; item.first = @"bla"; item.second = @"bla bla"; 

And I would like to pass this object to another method, which will then associate it with the context and store it.

So, is there a way to make a simple item.managedObjectContext = _context or something like that?

+4
source share
2 answers

This approach would be absolutely right ...

 Items *item = [[Item alloc] initWithEntity:entity insertIntoManagedObjectContext:nil]; item.first = @"blah"; item.second = @"blah blah"; 

You can then transfer this object to where it is needed, and when you are ready to transfer it to the context of the managed object, just insert it and save it.

 [managedObjectContext insertObject:item]; NSError *error = nil; [managedObjectContext save:&error]; 
+3
source

The standard init method for a subclass of NSManagedObject is -initWithEntity:insertIntoManagedObjectContext: If you do not provide a context, call:

 [myManagedObjectContext insertObject:item]; 

... this is what the init method does inside. You still need to save the managed entity as usual.

+1
source

Source: https://habr.com/ru/post/1346655/


All Articles