【问题标题】:Core Data error: nil is not a legal NSManagedObjectContext parameter核心数据错误:nil 不是合法的 NSManagedObjectContext 参数
【发布时间】:2017-10-18 11:52:12
【问题描述】:

我对创建 iOS 应用程序完全陌生。我必须快速创建一个表单应用程序,我可以在其中存储愿意填写的人的信息。基本上只是一堆用于姓名、邮件等内容的文本字段。

填写完表格后,我将使用以下代码存储他们的数据:

//Save action
NSEntityDescription *entityDesc = [NSEntityDescription entityForName:@"Person" inManagedObjectContext: context];
NSManagedObject *newPerson = [[NSManagedObject alloc]initWithEntity:entityDesc insertIntoManagedObjectContext:context];

//Fill in values
[newPerson setValue:self.btnPrefix.titleLabel.text forKey: @"prefix"];
[newPerson setValue:self.txtFirstName.text forKey: @"firstname"];
[newPerson setValue:self.txtLastName.text forKey: @"lastname"];
[newPerson setValue:self.txtLive.text forKey: @"country"];
[newPerson setValue:self.txtMail.text forKey: @"email"];
[newPerson setValue:self.txtPhone.text forKey: @"phonenumber"];
[newPerson setValue:self.txtLinked.text forKey: @"linkedIn"];
[newPerson setValue:self.txtAbout.text forKey: @"about"];

NSError *error;
[context save:&error];

在模拟器上执行时完全没有问题。但是一旦在 iPad 上运行,我就会得到这个错误:

由于未捕获的异常而终止应用程序 'NSInvalidArgumentException',原因:'+entityForName:nil 不是 搜索实体名称的合法 NSManagedObjectContext 参数 “人”

调试后在第一行触发:

NSEntityDescription *entityDesc = [NSEntityDescription entityForName:@"Person" inManagedObjectContext: context];

经过更多研究,我的 Appdelegate 在设备上运行时包含一个 nil persistentContainer,但在虚拟设备上运行时它被填充。所以我猜问题就在那里,但我找不到解决方法。

- (void)viewDidLoad {
    [super viewDidLoad];
    AppDelegate *appdelegate = (AppDelegate*)[[UIApplication sharedApplication]delegate];
    context = appdelegate.persistentContainer.viewContext;
}

谁能帮帮我?

【问题讨论】:

  • 错误告诉你,你的context参数是nil,一定不是这样。你如何得到你在那里传递的托管对象上下文对象?我假设你已经确保你的模型确实包含一个名为“Person”的实体,对吧?
  • viewDidLoad AppDelegate *appdelegate = (AppDelegate*)[[UIApplication sharedApplication]delegate]; context = appdelegate.persistentContainer.viewContext; 下。是的,我有一个包含实体 Person 的模型。正如我所说,它可以在模拟器上运行,所以我想只是缺少一些东西才能让它在物理设备上运行?
  • 经过一番研究,我的 Appdelegate 在设备上运行时包含一个 nil persistentContainer,但在虚拟设备上运行时它已被填充。所以我想问题就在那里,但我找不到解决方法。
  • 我假设您只是在为核心数据使用标准模板。那么为什么不看看你的应用程序代理默认的persistentContainer 方法呢?听起来您要么尝试在设备上没有写入权限的位置启动容器(模拟器通常在各个地方具有更多写入权限),要么您正面临设备上的竞速条件(您的视图控制器尝试在 loadPersistentStoresWithCompletionHandler: 方法完成之前访问容器和上下文)。
  • 没问题,在我看来,问这个问题有点“早”,但我意识到什么是“太早”,什么不取决于个人,而且你确实说你是新人。我很高兴你找到了这个问题的根源,我想现在你可以看到,对于那些没有你的项目并且有过类似经历的人来说,这很难弄清楚。我想防止您得出这样的结论:SO 上的人“高于”帮助新的编码员。 :) 再说一次,我很高兴你自己想出来了。

标签: ios objective-c ipad core-data


【解决方案1】:

对于遇到此错误的人。如果它在虚拟设备上工作但在物理设备上不工作,很可能是由于 iOS 9 和 10 之间访问核心数据的差异。

在 Xcode 8 中,AppDelegate 会自动为 iOS 10 生成数据,但如果您卡在 iOS 9 上,则需要在您的委托文件中添加以下代码:

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

- (NSURL *) applicationDocumentsDirectory{
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

- (NSManagedObjectModel *)managedObjectModel {
    if(_managedObjectModel != nil){
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"StylelabsForms" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

- (NSPersistentStoreCoordinator *) persistentStoreCoordinator{
    if(_persistentStoreCoordinator != nil){
        return _persistentStoreCoordinator;
    }

    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"StylelabsForms.sqlite"];
    NSError *error = nil;
    NSString *failureReason = @"Error loading saved data";
    if(![_persistentStoreCoordinator addPersistentStoreWithType: NSSQLiteStoreType configuration:nil URL: storeURL options:nil error:&error]){
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[NSLocalizedDescriptionKey] = @"Failed init application's saved data";
        dict[NSLocalizedFailureReasonErrorKey] = failureReason;
        dict[NSUnderlyingErrorKey] = error;
        error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }

    return _persistentStoreCoordinator;
}

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

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

    return _managedObjectContext;
}

同时调整保存如下:

- (void)saveContext {
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if(managedObjectContext != nil){
        NSError *error = nil;
        if([managedObjectContext hasChanges] && ![managedObjectContext save:&error]){
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }

    //For iOS 10 and above
    /*
    NSManagedObjectContext *context = self.persistentContainer.viewContext;
    NSError *error = nil;
    if ([context hasChanges] && ![context save:&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.
        NSLog(@"Unresolved error %@, %@", error, error.userInfo);
        abort();
    } */
}

【讨论】:

    【解决方案2】:

    私有惰性 var applicationDocumentsDirectory: URL = { // 应用程序用来存储 Core Data 存储文件的目录。此代码使用在应用程序的文档应用程序支持目录中命名的目录。 让 urls = FileManager.default.urls(对于:.documentDirectory,在:.userDomainMask) 返回网址[urls.count-1] }()

    private lazy var managedObjectModel: NSManagedObjectModel = {
        // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
        let modelURL = Bundle.main.url(forResource: "CoreData", withExtension: "momd")!
        return NSManagedObjectModel(contentsOf: modelURL)!
    }()
    
    private lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
        // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
        // Create the coordinator and store
        let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
        let url = self.applicationDocumentsDirectory.appendingPathComponent("CoreData.sqlite")
        var failureReason = "There was an error creating or loading the application's saved data."
        do {
            // Configure automatic migration.
            let options = [ NSMigratePersistentStoresAutomaticallyOption : true, NSInferMappingModelAutomaticallyOption : true ]
            try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: options)
        } catch {
            // Report any error we got.
            var dict = [String: AnyObject]()
            dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject?
            dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject?
    
            dict[NSUnderlyingErrorKey] = error as NSError
            let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
            // Replace this 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.
            NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
            abort()
        }
    
        return coordinator
    }()
    
    lazy var managedObjectContext: NSManagedObjectContext = {
    
        var managedObjectContext: NSManagedObjectContext?
        if #available(iOS 10.0, *){
    
            managedObjectContext = self.persistentContainer.viewContext
        }
        else{
        // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
        let coordinator = self.persistentStoreCoordinator
        managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
        managedObjectContext?.persistentStoreCoordinator = coordinator
    
        }
        return managedObjectContext!
    }()
    // iOS-10
    @available(iOS 10.0, *)
    lazy var persistentContainer: NSPersistentContainer = {
        /*
         The persistent container for the application. This implementation
         creates and returns a container, having loaded the store for the
         application to it. This property is optional since there are legitimate
         error conditions that could cause the creation of the store to fail.
         */
        let container = NSPersistentContainer(name: "CoreData")
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() 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.
    
                /*
                 Typical reasons for an error here include:
                 * The parent directory does not exist, cannot be created, or disallows writing.
                 * The persistent store is not accessible, due to permissions or data protection when the device is locked.
                 * The device is out of space.
                 * The store could not be migrated to the current model version.
                 Check the error message to determine what the actual problem was.
                 */
                fatalError("Unresolved error \(error)")
            }
        })
        print("\(self.applicationDocumentsDirectory)")
        return container
    }()
    

    【讨论】:

    • 上面的代码解决了我第一次检查coredata是否存在的问题。迅速 3.
    猜你喜欢
    • 2012-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-06
    • 2014-09-28
    • 2013-01-19
    • 1970-01-01
    相关资源
    最近更新 更多