Search code examples
iosobjective-ccore-datamagicalrecord

Default Context is nil! Did you forget to initialize the Core Data Stack? [MagicalRecord]


I'm using MagicalRecord for the first time.

I've set it up like this:

[MagicalRecord setupCoreDataStackWithStoreNamed:@"test"];

where test is the filename of my Core data file ( test.xcdatamodeld ).

In my view controller where I want to use my core data I wrote this:

- (void)viewDidLoad
{
    [super viewDidLoad];

    // If there is no POI, create a new POI
    if (!_poi) {
        _poi = [POI MR_createEntity];
    }
    // If there is no POI rank(=category) create one
    if (!_poi.rank) {
        _poi.rank = [Rank MR_createEntity];
    }
}

Where I did

@Class POI; 

in the header file. Where POI and Rank are my coredata classes that are generated by xCode.

When I run this: I always get:

2014-08-08 14:52:05.509 test[41248:60b] *** Assertion failure in +[NSManagedObjectContext MR_defaultContext], /Users/x/Documents/xCode/test/test/Pods/MagicalRecord/MagicalRecord/Categories/NSManagedObjectContext/NSManagedObjectContext+MagicalRecord.m:60
2014-08-08 14:52:05.512 test[41248:60b] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Default Context is nil! Did you forget to initialize the Core Data Stack?'

This happens just after the init of my ViewController.

Can someone help me?

EDIT:

I installed it via Cocoapods:

Pod 'MagicalRecord'

My Appdelegate:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    //Setup Reliant
    [self _reliantInit];

    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.rootViewController = [[UINavigationController alloc]initWithRootViewController:[[HomeViewController alloc]init]];
    // Override point for customization after application launch.
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];

    //Setup MagicalRecord
    [MagicalRecord setupCoreDataStackWithStoreNamed:@"test"];

    return YES;
}

Solution

  • You're doing things in the wrong order. viewDidLoad of the root view controller will be called before your core data setup code, since you're adding it to the window straight away. Move the magical record setup to the top of the app delegate method.