I'm relative new with CoreData and I want to know if I'm doing the things right. First the documentation says:
"By convention, you get a context from a view controller. You must implement your application appropriately, though, to follow this pattern.
When you implement a view controller that integrates with Core Data, you can add an NSManagedObjectContext property.
When you create a view controller, you pass it the context it should use. You pass an existing context, or (in a situation where you want the new controller to manage a discrete set of edits) a new context that you create for it. It’s typically the responsibility of the application delegate to create a context to pass to the first view controller that’s displayed."
https://developer.apple.com/library/ios/documentation/DataManagement/Conceptual/CoreDataSnippets/Articles/stack.html
so what I do is 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 any place I want to do some change to the database I do this.
MainNexarAppDelegate *appDelegate =
[[UIApplication sharedApplication] delegate];
self.moc = [[NSManagedObjectContext alloc] init];
self.moc.persistentStoreCoordinator = [appDelegate persistentStoreCoordinator];
/*code**/
[self.moc save:&error];
2-.And if I'm going to work in a different thread I have my custom method to create the NSManagedObjectContext with NSPrivateQueueConcurrencyType so it can be manage 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;
- Is a good practice create a NSManagedObjectContext for each view controller where you will do some change to the database?
1.1. It's a valid approach use [UIApplication sharedApplication] to get the persistent NSPersistentStoreCoordinator form the appdelegate? - It's safe to share the persistent store coordinator between the main thread and any other thread?
Any help will be appreciated :).