【问题标题】:+entityForName: nil is not a legal NSManagedObjectContext parameter searching for entity name 'Scores'+entityForName: nil 不是搜索实体名称“分数”的合法 NSManagedObjectContext 参数
【发布时间】:2015-04-06 15:48:50
【问题描述】:

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

当尝试查找带有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];

【问题讨论】:

  • 调试,检查context是否存在。崩溃前记录的任何错误?
  • 检查值和/或上下文是否存在的最佳方法是什么?只需将其记录到控制台还是?
  • 可以,或者加个断点和po
  • 好的,如果我在下面定义*context 的地方注释掉所有内容,我不会崩溃,如果我尝试记录上下文,控制台将一无所获。嗯
  • 因此您需要查看 + 显示您的 managedObjectContext 方法实现,并查看您的核心数据堆栈是否正在设置中

标签: ios objective-c core-data


【解决方案1】:

好的,所以,并不是说应用程序委托应该拥有核心数据堆栈,而是目前您拥有它,并且拥有核心数据堆栈的实例需要创建堆栈 - 目前什么都没有做那个。

你只有

@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;
}

【讨论】:

  • 啊,那段代码除了导入coredata框架到实现文件外,没有崩溃。好的,现在开始下一项工作,检查数据库 :) 谢谢!
猜你喜欢
  • 2015-07-06
  • 2014-09-28
  • 2013-12-26
  • 2014-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多