+ entityForName:nil不是合法的NSManagedObjectContext参数,用于搜索实体名称“Scores”

时间:2015-04-06 15:48:51

标签: ios objective-c core-data

我是Objective C,iOS和CoreData的新手,我正在尝试将一些数据保存到CoreData中的Entity。

尝试使用insertNewObjectForEntityForName查找实体时,看起来它会根据以下错误返回nil

任何帮助将不胜感激!

错误:

2015-04-06 17:46:12.274 Bugland[18623:607] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', 
reason: '+entityForName: nil is not a legal NSManagedObjectContext parameter searching for entity name 'Scores''

LeaderboardViewController.m

    JPAppDelegate *JPAppDelegate = [[UIApplication sharedApplication] delegate];

    NSManagedObjectContext *context =[JPAppDelegate managedObjectContext];

    NSManagedObject *newScore;
    newScore = [NSEntityDescription
                insertNewObjectForEntityForName:@"Scores"
                inManagedObjectContext:context];
    [newScore setValue: scoreToAddAsString forKey:@"score"];
    NSError *error;
    [context save:&error];

1 个答案:

答案 0 :(得分:3)

好吧,那么,不是应用程序委托应该拥有核心数据堆栈,但是现在你已经拥有它,并且拥有核心数据堆栈的实例需要创建堆栈 - 此刻什么都没做这一点。

你所拥有的只是

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

它只是创建了一些存取方法。什么都没有设置这些实例变量。

你应该有一些代码如下面的庞然大物,另见this

- (NSManagedObjectContext *)managedObjectContext {

    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }

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

/**
 Returns the managed object model for the application.
 If the model doesn't already exist, it is created by merging all of the models found in the application bundle.
 */
- (NSManagedObjectModel *)managedObjectModel {

    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    _managedObjectModel = [NSManagedObjectModel mergedModelFromBundles:nil];
    return _managedObjectModel;
}

/**
 Returns the URL to the application's documents directory.
 */
- (NSURL *)applicationDocumentsDirectory
{
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

/**
 Returns the persistent store coordinator for the application.
 If the coordinator doesn't already exist, it is created and the application's store added to it.
 */
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {

    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }

    // copy the default store (with a pre-populated data) into our Documents folder
    //
    NSString *documentsStorePath =
        [[[self applicationDocumentsDirectory] path] stringByAppendingPathComponent:@"Recipes.sqlite"];

    // if the expected store doesn't exist, copy the default store
    if (![[NSFileManager defaultManager] fileExistsAtPath:documentsStorePath]) {
        NSString *defaultStorePath = [[NSBundle mainBundle] pathForResource:@"Recipes" ofType:@"sqlite"];
        if (defaultStorePath) {
            [[NSFileManager defaultManager] copyItemAtPath:defaultStorePath toPath:documentsStorePath error:NULL];
        }
    }

    _persistentStoreCoordinator =
        [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];

    // add the default store to our coordinator
    NSError *error;
    NSURL *defaultStoreURL = [NSURL fileURLWithPath:documentsStorePath];
   if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType
                                                  configuration:nil
                                                            URL:defaultStoreURL
                                                        options:nil
                                                          error:&error]) {
        /*
         Replace this implementation with code to handle the error appropriately.

         abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.

         Typical reasons for an error here include:
         * The persistent store is not accessible
         * The schema for the persistent store is incompatible with current managed object model
         Check the error message to determine what the actual problem was.
         */
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }

    // setup and add the user's store to our coordinator
    NSURL *userStoreURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"UserRecipes.sqlite"];
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType
                                                                     configuration:nil
                                                                               URL:userStoreURL
                                                                           options:nil
                                                                             error:&error]) {
        /*
         Replace this implementation with code to handle the error appropriately.

         abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.

         Typical reasons for an error here include:
         * The persistent store is not accessible
         * The schema for the persistent store is incompatible with current managed object model
         Check the error message to determine what the actual problem was.
         */
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }

    return _persistentStoreCoordinator;
}