开发者

How to use the managed data context from a modal view? (Core Data)

开发者 https://www.devze.com 2023-03-13 10:01 出处:网络
I have a Core Data structure set up. In my application delegate, I have: - (void)applicationDidFinishLaunching:(UIApplication *)application

I have a Core Data structure set up. In my application delegate, I have:

    - (void)applicationDidFinishLaunching:(UIApplication *)application
{    

    // Configure and show the window.

    RootViewController *rootViewController = [[RootViewController alloc] initWithStyle:UITableViewStylePlain];

    NSManagedObjectContext *context = [self managedObjectContext];
    if (!context) {
        // Handle the error.
    }
    rootViewController.managedObjectContext = context;

    UINavigationController *aNavigationController = [[UINavigationController alloc] initWithRootViewController:rootViewController];
    self.navigationController = aNavigationController;

    [_window addSubview:[_navigationController view]];
    [_window makeKeyAndVisible];

    [rootViewController release];
}

Tl;dr: This code sets up a pointer to the开发者_开发问答 managed object context for my data, and then sets the root view controller's managedObjectContext to its managedObjectContext.

So then, I pull up a modal view, to let the user add data. But to save this data, I need access to the managedObjectContext context because this is how you save the data...

foo *myFoo = (foo *)[NSEntityDescription insertNewObjectForEntityForName:@"Foo" inManagedObjectContext:managedObjectContext];

...but I can't call that without having access to the managed object context.? How do I access the rootViewController's managedObjectContext from a modal view.


I encountered this problem and thought of two solutions.

  1. Pass the data to the root view controller in a dictionary (through NSNotificationCenter) and have it save.

  2. Pass the ManagedObjectContext (MOC) into the modal view controller and let the modal view's MOC do the saving.

I ended up going with #2 for a few reasons.

  • It ends up being easier when saving more than simple data.
  • Making a userInfo docionary is messy.
  • A "add entity" dialog should be able to add an entity, right?

To implement this, in your UIViewController subclass, simply add a property like this:

//... In your interface:
NSManagedObjectContext *moc;

//... beneath your interface:
@property (nonatomic, retain) NSManagedObjectContext *moc;

Then don't forget to synthesized and release as necessary. Next, in your root view, pass in the context before presenting the mod view:

//... Create Modal VC, then...
[modalViewController setMOC:self.managedObjectContext];
// Now, present the modal VC

Boom, you have an MOC in your modal view. Call save as necessary. Note that if you forget to pass in the MOC, your app will crash when you attempt to execute a fetch request.

0

精彩评论

暂无评论...
验证码 换一张
取 消