Core Data - Basic Questions
I would like to know how the following works in Objective-C
in my header file i have the following which is initialized from a different view controller
@interface UserLookup : UIViewController { NSManagedObjectContext *referringObject; }
and in my implementation file i have to pass this NSManagedObjectContext
to 2 child vie开发者_如何学Gow controller then does it make a difference which view controller is called first... and does the NSManagedObjectContext
changes in any one of the child controller?
Regards
You don't really need to pass it around to every view controller where you will need Core Data access - just use
NSManagedObjectContext* moc = [(MyAppDelegateClass *)[[UIApplication sharedApplication] delegate] managedObjectContext];
managedObjectContext
must be an accessible ivar of your app delegate.
It makes it conceptually similar too. There is one NSManagedObjectContext (in most uncomplicated apps, thought you can have multiples), owned by your app delegate. You don't ever retain or release it (except for when it is created in the app delegate, on first access if you are using Apple's template code, and when it is released in app delegate's dealloc
.
ASFAIK it should not make a difference which viewController is used first. Think of the NSManagedObjectContext as a pointer to the physical datasource.
You can add and remove NSManagedObjects from the context. But these changes are only saved to disk when you call the save:
method.
Does that help at all?
To use only one context is simple and works fine. But you can also create a new managed object context and pass it to the other view controller. Though the persistent store is only one, but you can have multiple contexts.
Each context have each undo manager, so you can control changes of managed objects in the context. You can save changes in only one context even if the other context has also some changes. After saving a context, you can merge the changes of two contexts by the following NSManagedObjectContext instance methods:
- (void)mergeChangesFromContextDidSaveNotification:(NSNotification *)notification
- (void)refreshObject:(NSManagedObject *)object mergeChanges:(BOOL)flag
Maybe this document helps you to understand more detail. http://developer.apple.com/library/ios/#documentation/DataManagement/Conceptual/CoreDataSnippets/Articles/stack.html
And the CoreDataBooks Apple sample code uses the additional context.
精彩评论