managedObjectContext é nulo
Estou tentando adicionar o Core Data a um projeto existente. Eu tenho:
1) adicionou o Core Data framework 2) adicionou os acessores e propriedades para o AppDelegate 3) criou o arquivo de modelo de dados
Agora quando tento ligarNSManagedObjectContext *context = [self managedObjectContext];
a partir de um controlador de visualização, o contexto é nulo e o managedObjectContext nunca é acionado.
Aqui está o AppDelegate:
<code>#import "XXXAppDelegate.h" #import <CoreData/CoreData.h> @implementation XXXAppDelegate @synthesize window=_window; @synthesize navigationController=_navigationController; @synthesize managedObjectContext = _managedObjectContext; @synthesize managedObjectModel = _managedObjectModel; @synthesize persistentStoreCoordinator = _persistentStoreCoordinator; - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Override point for customization after application launch. // Add the navigation controller's view to the window and display. self.window.rootViewController = self.navigationController; [self.window makeKeyAndVisible]; return YES; } // Explicitly write Core Data accessors - (NSManagedObjectContext *) managedObjectContext { if (managedObjectContext != nil) { return managedObjectContext; } NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator]; if (coordinator != nil) { managedObjectContext = [[NSManagedObjectContext alloc] init]; [managedObjectContext setPersistentStoreCoordinator: coordinator]; } return managedObjectContext; } - (NSManagedObjectModel *)managedObjectModel { if (managedObjectModel != nil) { return managedObjectModel; } managedObjectModel = [NSManagedObjectModel mergedModelFromBundles:nil]; return managedObjectModel; } - (NSPersistentStoreCoordinator *)persistentStoreCoordinator { if (persistentStoreCoordinator != nil) { return persistentStoreCoordinator; } NSURL *storeUrl = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] stringByAppendingPathComponent: @"<Project Name>.sqlite"]]; NSError *error = nil; persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]]; if(![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:nil error:&error]) { /*Error for store creation should be handled in here*/ } return persistentStoreCoordinator; } - (NSString *)applicationDocumentsDirectory { return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; } @end </code>
EDIT: aqui é o meu código do controlador de visualização
<code>NSManagedObjectContext *context = [self managedObjectContext]; NSManagedObject *cardSet = [NSEntityDescription insertNewObjectForEntityForName:@"CardSet" inManagedObjectContext:context]; [cardSet setValue:@"Set 1" forKey:@"cardSetName"]; </code>