I am relatively new with CoreData and I want to know if I am doing this correctly. The documentation first says:
“By convention, you get context from the view controller. You must implement your application accordingly, but follow this pattern.
When you implement a view controller that integrates with Core Data, you can add the NSManagedObjectContext property.
When you create a view controller, you pass it the context that it should use. You are transferring an existing context or (in a situation where you want the new controller to control a discrete set of changes), the new context that you create for it. Typically, it is the responsibility of the application delegate to create the context for the transition to the first view controller that is displayed. "
https://developer.apple.com/library/ios/documentation/DataManagement/Conceptual/CoreDataSnippets/Articles/stack.html
so I create a property for my NSManagedObjectContext:
MyViewController.H @interface MyViewController : ViewController { NSManagedObjectContext *moc; } @property (nonatomic, retain) NSManagedObjectContext *moc; @end MyViewController.m @implementation MyViewController @synthesize moc=moc;
1. - And anywhere I want to add to the database, I do it.
MainNexarAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate]; self.moc = [[NSManagedObjectContext alloc] init]; self.moc.persistentStoreCoordinator = [appDelegate persistentStoreCoordinator]; [self.moc save:&error];
2-. And if I'm going to work in another thread, I have my own method for creating an NSManagedObjectContext with NSPrivateQueueConcurrencyType so that it can be managed in a private queue:
//Myclass NSObject<br> -(NSManagedObjectContext *)createManagedObjectContext{ MainNexarAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate]; NSPersistentStoreCoordinator *coordinator = [appDelegate persistentStoreCoordinator]; if (coordinator != nil) { __managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType]; [__managedObjectContext setPersistentStoreCoordinator:coordinator]; } return __managedObjectContext; } //__managedObjectContext is my property from the .h file //@property (readonly,strong,nonatomic) NSManagedObjectContext* managedObjectContext;
- It is good practice to create an NSManagedObjectContext for each view controller, where will you make some changes to the database?
1.1. Is this a valid approach that uses [UIApplication sharedApplication] to get a permanent NSPsistentStoreCoordinator from appdelegate?
- Is it safe to share the persistent storage coordinator between the main thread and any other thread?
Any help would be appreciated :).
ios objective-c core-data
Moy
source share