managedObjectContext in Other View
I have finally managed to get core data working and beginning to understand it. So far I have just been playing in a window based app with core data enabled, playing inside the app delegate files.
But how can I access my managedObjectContext from outside the app delegate, for example if 开发者_开发百科I had a UIView subclass?
Try using
[[[UIApplication sharedApplication] delegate] managedObjectContext];
To get rid of warnings, cast the delegate as your actual AppDelegate; for example,
NSManagedObjectContext *context = [(YourAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
EDIT:
After you change up any data, you'll need to save it. Here's the method I use:
NSManagedObjectContext *moc = [self managedObjectContext];
NSError *error;
if (![moc save:&error]) {
NSLog(@"Couldn't save current data in current method.");
}
Change up the log statement as you see fit.
精彩评论