Search code examples
ioscocoa-touchcore-dataios7delegates

Crash on retrieving managedObjectContext from app delegate


So I am getting a EXC_BAD_ACESS(code=2...) error when I try to retrieve my managedObjectContext in one of my view controllers.

This is my code for the getter method:

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

    return self.managedObjectContext;
}

This is how I try to retrieve the managedObjectContext

QVAppDelegate *appDelegate = (QVAppDelegate*)[[UIApplication sharedApplication] delegate];
self.managedObjectContext = appDelegate.managedObjectContext;

Here are the definitions in the appDelegate

@property (strong, nonatomic) NSManagedObjectModel *managedObjectModel;
@property (strong, nonatomic) NSManagedObjectContext *managedObjectContext;
@property (strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;

I am using ARC and converted this tutorial's code to ARC.

I really can't seem to be able to solve this.

Edit: Here is where it crashes https://i.sstatic.net/05Det.png


Solution

  • You appear to have an infinite loop in here:

    - (NSManagedObjectContext *) managedObjectContext {
        if (self.managedObjectContext != nil) {
            return self.managedObjectContext;
        }
    

    self.managedObjectContext translates to [self managedObjectContext] which is the method you just entered. So you are calling the accessor over and over again.

    You did not copy that example correctly.

    Second, you really should be using dependency injection instead of treating your App Delegate like a singleton. I would strongly suggest researching DI and employing that design pattern. It will save you a lot of pain later.

    Update 1

    Where does it crash? What line of code? Is it self.managedObjectContext = appDelegate.managedObjectContext; or somewhere else? Where is your breakpoint firing in Xcode? If it is firing at that line of code and not inside of the -managedObjectContext method then you have a problem with your App Delegate (which should not be possible).