xil3
xil3

Reputation: 16449

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?

Upvotes: 5

Views: 2451

Answers (2)

Seamus Campbell
Seamus Campbell

Reputation: 17916

The standard init method for an NSManagedObject subclass is -initWithEntity:insertIntoManagedObjectContext:. If you don't provide a context, call:

[myManagedObjectContext insertObject:item];

...which is what the init method does internally. You'll still need to save the managedObjectContext as usual.

Upvotes: 1

Mark Adams
Mark Adams

Reputation: 30846

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];

Upvotes: 4

Related Questions