2015-04-04 3 views
0

Я пытаюсь сделать мое приложение сохранить основные данные в AppDelegate.swift, но при выходе из приложения, она падает с этим журналом в консоли:Почему мое приложение рушится при попытке сохранить данные ядра?

2015-04-04 22:04:38.043 myapp[14882:714850] CoreData: error: -addPersistentStoreWithType:SQLite configuration:(null) URL:file:///Users/kiancross/Library/Developer/CoreSimulator/Devices/59D353AF-8C56-42D6-8B35-9F51FE04D1BC/data/Containers/Data/Application/66D76678-B819-4B01-8172-6324BB5D2E7B/Documents/myappsqlite options:(null) ... returned error Error Domain=NSCocoaErrorDomain Code=134100 "The operation couldn’t be completed. (Cocoa error 134100.)" UserInfo=0x7fc453dcb120 {metadata={ 
    NSPersistenceFrameworkVersion = 519; 
    NSStoreModelVersionHashes =  { 
     SavedData = <f13dc99c 2ebf5dd2 a89322cb 537a0f94 361477df 04077315 5954c0b5 afd3f9a1>; 
    }; 
    NSStoreModelVersionHashesVersion = 3; 
    NSStoreModelVersionIdentifiers =  (
     "" 
    ); 
    NSStoreType = SQLite; 
    NSStoreUUID = "E748E18D-F898-4AC1-96A4-7F8F1925D369"; 
    "_NSAutoVacuumLevel" = 2; 
}, reason=The model used to open the store is incompatible with the one used to create the store} with userInfo dictionary { 
    metadata =  { 
     NSPersistenceFrameworkVersion = 519; 
     NSStoreModelVersionHashes =   { 
      SavedData = <f13dc99c 2ebf5dd2 a89322cb 537a0f94 361477df 04077315 5954c0b5 afd3f9a1>; 
     }; 
     NSStoreModelVersionHashesVersion = 3; 
     NSStoreModelVersionIdentifiers =   (
      "" 
     ); 
     NSStoreType = SQLite; 
     NSStoreUUID = "E748E18D-F898-4AC1-96A4-7F8F1925D369"; 
     "_NSAutoVacuumLevel" = 2; 
    }; 
    reason = "The model used to open the store is incompatible with the one used to create the store"; 
} 
2015-04-04 22:04:38.047 myapp[14882:714850] Unresolved error Optional(Error Domain=YOUR_ERROR_DOMAIN Code=9999 "Failed to initialize the application's saved data" UserInfo=0x7fc453dcce00 {NSLocalizedDescription=Failed to initialize the application's saved data, NSLocalizedFailureReason=There was an error creating or loading the application's saved data., NSUnderlyingError=0x7fc453db2360 "The operation couldn’t be completed. (Cocoa error 134100.)"}), Optional([NSLocalizedDescription: Failed to initialize the application's saved data, NSLocalizedFailureReason: There was an error creating or loading the application's saved data., NSUnderlyingError: Error Domain=NSCocoaErrorDomain Code=134100 "The operation couldn’t be completed. (Cocoa error 134100.)" UserInfo=0x7fc453dcb120 {metadata={ 
    NSPersistenceFrameworkVersion = 519; 
    NSStoreModelVersionHashes =  { 
     SavedData = <f13dc99c 2ebf5dd2 a89322cb 537a0f94 361477df 04077315 5954c0b5 afd3f9a1>; 
    }; 
    NSStoreModelVersionHashesVersion = 3; 
    NSStoreModelVersionIdentifiers =  (
     "" 
    ); 
    NSStoreType = SQLite; 
    NSStoreUUID = "E748E18D-F898-4AC1-96A4-7F8F1925D369"; 
    "_NSAutoVacuumLevel" = 2; 
}, reason=The model used to open the store is incompatible with the one used to create the store}]) 

код, который вызвав эту ошибку в моем AppDelegate.swift является:

func applicationDidEnterBackground(application: UIApplication) { 
     // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
     // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. 


     let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate 
     let managedContext = appDelegate.managedObjectContext! 

     let entity = NSEntityDescription.entityForName("SavedData", inManagedObjectContext: managedContext) 


     let managedObject = NSManagedObject(entity: entity!, insertIntoManagedObjectContext:managedContext) 

     managedObject.setValue(sharedData.jsonUrl, forKey: "jsonUrl") 

     var error: NSError? 
     if !managedContext.save(&error) { 
      println("Could not save \(error), \(error?.userInfo)") 
     } 

    } 

Это модель моего CoreData; вы можете увидеть снимок экрана ниже:

core data screen shot

Как вы можете видеть, что есть все, что нужно иметь в нем.

Вопрос в том, какая часть моего кода вызывает этот крах? Я последовал за this учебным пособием по внедрению CoreData в приложениях, и я почти уверен, что следил за ним настолько точно, насколько это было возможно для удовлетворения потребностей моих приложений.

Спасибо,

+1

См. [Вопрос]/[http://stackoverflow.com/q/8078337/3985749] вопрос/ответ. Простое исправление - это просто удалить приложение и повторный запуск. – pbasdf

ответ

1

Я не очень уверен, но последняя строка вашей ошибки говорит: reason=The model used to open the store is incompatible with the one used to create the store}]) что означает, что DataModel из CoreData не то же самое, как тот, который вы используете.

Просто удалите приложение (LongPress на значок приложения и удалите его) и запустите его снова, и это решит хотя бы эту проблему.

Лучшее объяснение here

Удалить приложение из тренажера и выполнить чистую над проектом. Это должно устранить эти проблемы. Убедитесь, что вы не работаете в отладчике при удалении приложения, иначе он фактически не удалит его.

Если вы хотите убедиться, что его нет, ознакомьтесь с этим каталогом Пользователи/INSERT_YOUR_USER_HERE/Библиотека/Поддержка приложений/iPhone Simulator/для папки вашего приложения под версией, в которой вы работаете.

Примечание: это только для разработки. Для производства вам необходимо выполнить некоторую миграцию. Google «Первичная миграция данных», при этом облегченная миграция является самой простой ».

Смежные вопросы