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

后端 未结 2 1161
谎友^
谎友^ 2021-01-18 20:04

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

相关标签:
2条回答
  • 2021-01-18 20:09

    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];
    
    0 讨论(0)
  • 2021-01-18 20:28

    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.

    0 讨论(0)
提交回复
热议问题