Question

I've been following some examples online for using NSManagedObjectContext. It seems that while none of the examples manually initialize the instance of NSManagedObjectContext in the didFinishLoadingWithOptions method in AppDelegate, you must set _managedObjectContext to self.managedObjectContext. This doesn't seem necessary in other classes, such as controllers?

@synthesize managedObjectContext = _managedObjectContext;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    if (_managedObjectContext == 0) {
        // This is the output shown in the log.
        NSLog(@"Not set.");
    } else {
        NSLog(@"It's set!");
    }

    if (self.managedObjectContext == 0) {
        NSLog(@"Not set.");
    } else {
        // This is the output shown in the log.
        NSLog(@"It's set!");
    }

    // Should this line be necessary?
    _managedObjectContext = [self managedObjectContext];

    _navigationController = (UINavigationController*)self.window.rootViewController;
    _chordViewController = (ChordViewController*) _navigationController.topViewController;
    [_chordViewController setManagedObjectContext: _managedObjectContext];
    return YES;
}
Was it helpful?

Solution

That line shouldn't be necessary at all.

You've basically set the managedObjectContext variable to itself. It won't technically harm anything, but it isn't helpful either.

In your app delegate file you should have a bunch of boiler plate code to create and manage the context. If you don't, it's likely because you didn't select the "Use Core Data" option when creating the project. When you are creating a new project to use core data, make sure you check that box. It will ensure that the proper code to create the managed object context is inserted in your app delegate file.

EDIT: Ensure that you have this code in your app delegate:

// Returns the managed object context for the application.
// If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
- (NSManagedObjectContext *)managedObjectContext
{
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }

    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (coordinator != nil) {
        _managedObjectContext = [[NSManagedObjectContext alloc] init];
        [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    }
    return _managedObjectContext;
}

If that code is there, you should be all set. Core data is a tricky subject to get a handle on, but it should be working properly with that boiler plate code. You should ALWAYS call self.managedObjectContext to ensure that this method is called. Do not try to access _managedObjectContext directly. That will circumvent the code that properly initializes the MOC in the first place.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top