Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I associate an NSManagedObject to the context after it has been initialised?

For example, if I have an NSManagedObject named Items, and I want to set the ManagedObjectContext later (not when initialised), how would I do that?

At the moment I'm doing this:

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

That automatically associates it to _context.

But what if I want to do this:

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

And I would want to pass that object to another method which would then associate it with the context and save it.

So is there any way to just do a simple item.managedObjectContext = _context or something like that?

like image 598
xil3 Avatar asked Apr 05 '11 04:04

xil3


People also ask

What is NSManagedObject context?

An object space to manipulate and track changes to managed objects.

How do I set up NSManagedObject?

From the Xcode menu bar, choose Editor > Create NSManagedObject Subclass. Select your data model, then the appropriate entity, and choose where to save the files. Xcode places both class and properties files into your project.

What is context in Core Data?

From your perspective, the context is the central object in the Core Data stack. It's the object you use to create and fetch managed objects, and to manage undo and redo operations. Within a given context, there is at most one managed object to represent any given record in a persistent store.


1 Answers

This approach would be perfectly valid...

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

You're then free to pass this object around to where its needed and when you're ready to commit it to a managed object context, simply insert it and save.

[managedObjectContext insertObject:item];
NSError *error = nil;
[managedObjectContext save:&error];
like image 196
Mark Adams Avatar answered Sep 29 '22 11:09

Mark Adams