2017-05-18 39 views
1

我是創建iOS應用程序的新手。我必須快速創建一個表單應用程序,我可以從願意填寫信息的人那裏存儲信息。基本上只是一堆文本字段,如名稱,郵件等。核心數據錯誤:nil不是合法的NSManagedObjectContext參數

表單填寫完成後,使用這一位代碼存儲他們的數據:

//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上運行我得到這個錯誤:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+entityForName: nil is not a legal NSManagedObjectContext parameter searching for entity name 'Person''

調試它就會在第一行triggerd後:

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

了些研究後,我的AppDelegate包含零persistentContainer當跑設備,但在虛擬設備上運行時會填充它。所以我想問題在那裏,但我找不到解決問題的方法。

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

任何人都可以幫我嗎?

+0

錯誤告訴你,你的'context'參數是'nil',不一定是這種情況。你如何獲得你傳入的託管對象上下文對象?我假設你確保你的模型確實包含一個名爲「Person」的實體,對嗎? – Gero

+0

under ** viewDidLoad **'AppDelegate * appdelegate =(AppDelegate *)[[UIApplication sharedApplication] delegate]; context = appdelegate.persistentContainer.viewContext;'。是的,我有一個包含實體Person的模型。正如我所說的,它可以在模擬器上工作,所以我想只有一件東西可以讓它在物理設備上工作? – Akorna

+0

經過一番研究後,我的Appdelegate在設備上運行時包含一個零persistentContainer,但是它在虛擬設備上運行時被填充。所以我想問題在那裏,但我找不到解決問題的方法。 – Akorna

回答

2

對於遇到此錯誤的人。最有可能的是,如果它在虛擬設備上工作,但不在物理設備上,這是由於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(); 
    } */ 
} 
0

私人懶VAR applicationDocumentsDirectory:URL = {// 目錄th e應用程序用於存儲Core Data存儲文件。此代碼使用應用程序的文檔Application Support目錄中指定的目錄。 讓網址= 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 
}() 
+0

上面的代碼解決了我第一次檢查coredata是否存在的問題。在迅速3。 – komara

相關問題