2015-02-20 3 views
2

Я делаю быстрое приложение, где мне нужно предварительно загрузить данные ядра. Для этого я создал еще одно примерное приложение для iOS, которое использует то же самое datamodel, что и основное приложение. Этот образец создает sqlite-файл с данными в нем. Я скопировал файлы sqlite (.sqlite и 2 .sqlite- *), созданные образцовым приложением, с данными в пакет ресурсов основного приложения, а мой код в «persistentStoreCoordinator» показан ниже.Предварительная загрузка данных в основные данные в приложении iOS 8

lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { 
    // The persistent store coordinator for the application. This implementation creates and return 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 
    var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) 
    let url: NSURL = self.applicationDocumentsDirectory.URLByAppendingPathComponent("myAssistant.sqlite") 

    //---------------------------------------------------------------------------- 
    // Add the below code 
    // Check if a data store already exists in the documents directory. 

    var checker: Bool = NSFileManager.defaultManager().fileExistsAtPath(url.path!) 

    if (!checker){ 
     // If there’s no Data Store present (which is the case when the app first launches), identify the sqlite file we added in the Bundle Resources, copy it into the Documents directory, and make it the Data Store. 

     var sqlitePath: NSString = NSBundle.mainBundle().pathForResource("myAssistant", ofType: "sqlite")! 
     NSFileManager.defaultManager().copyItemAtPath(sqlitePath, toPath: url.path!, error: nil) 

    } 
    //----------------------------------------------------------------------------/ 

    var error: NSError? = nil 
    var failureReason = "There was an error creating or loading the application's saved data." 

    if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil { 
     coordinator = nil 
     // Report any error we got. 
     let dict = NSMutableDictionary() 
     dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" 
     dict[NSLocalizedFailureReasonErrorKey] = failureReason 
     dict[NSUnderlyingErrorKey] = error 
     error = 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 \(error), \(error!.userInfo)") 
     abort() 
    } 

Тем не менее, основные ошибки приложения с ошибкой ниже.

2015-02-19 18:23:37.235 myAssistant[10477:488435] CoreData: error: -addPersistentStoreWithType:SQLite configuration:(null) URL:file:///Users/NishiJain/Library/Developer/CoreSimulator/Devices/428084BE-0E2B-4F58-A274-AED2C76845DF/data/Containers/Data/Application/7F478A95-CD1E-4C99-BF62-60DAA39C6C11/Documents/myAssistant.sqlite options:(null) ... returned error Error Domain=NSCocoaErrorDomain Code=134100 "The operation couldn’t be completed. (Cocoa error 134100.)" UserInfo=0x7f9c11e4e760 {metadata={ 
NSPersistenceFrameworkVersion = 519; 
NSStoreModelVersionHashes =  { 
    Category = <be1d87d2 e4c72a88 a830fb54 b9aea852 7887b5a6 bf2f85bb 22e878d0 c6916d06>; 
    ListDetails = <2cc64684 6520b473 d4bc4ae5 39f66fa0 0437788e ef1a0d91 1bdd7b52 86c0fbf2>; 
    Lists = <c2491da1 58622f56 64112d31 ba3e294a 1167e3f1 5427cd3a a56c1613 e2c0ee8a>; 
}; 
NSStoreModelVersionHashesVersion = 3; 
NSStoreModelVersionIdentifiers =  (
    "" 
); 
NSStoreType = SQLite; 
NSStoreUUID = "F84E0B5C-F83B-48ED-9043-5F9B6752FCA4"; 
"_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 =   { 
     Category = <be1d87d2 e4c72a88 a830fb54 b9aea852 7887b5a6 bf2f85bb 22e878d0 c6916d06>; 
     ListDetails = <2cc64684 6520b473 d4bc4ae5 39f66fa0 0437788e ef1a0d91 1bdd7b52 86c0fbf2>; 
     Lists = <c2491da1 58622f56 64112d31 ba3e294a 1167e3f1 5427cd3a a56c1613 e2c0ee8a>; 
    }; 
    NSStoreModelVersionHashesVersion = 3; 
    NSStoreModelVersionIdentifiers =   (
     "" 
    ); 
    NSStoreType = SQLite; 
    NSStoreUUID = "F84E0B5C-F83B-48ED-9043-5F9B6752FCA4"; 
    "_NSAutoVacuumLevel" = 2; 
}; 
reason = "The model used to open the store is incompatible with the one used to create the store"; 
} 
2015-02-19 18:23:37.243 myAssistant[10477:488435] Unresolved error Optional(Error Domain=YOUR_ERROR_DOMAIN Code=9999 "Failed to initialize the application's saved data" UserInfo=0x7f9c11f27600 {NSLocalizedFailureReason=There was an error creating or loading the application's saved data., NSLocalizedDescription=Failed to initialize the application's saved data, NSUnderlyingError=0x7f9c11e4e7a0 "The operation couldn’t be completed. (Cocoa error 134100.)"}), Optional([NSLocalizedFailureReason: There was an error creating or loading the application's saved data., NSLocalizedDescription: Failed to initialize the application's saved data, NSUnderlyingError: Error Domain=NSCocoaErrorDomain Code=134100 "The operation couldn’t be completed. (Cocoa error 134100.)" UserInfo=0x7f9c11e4e760 {metadata={ 
NSPersistenceFrameworkVersion = 519; 
NSStoreModelVersionHashes =  { 
    Category = <be1d87d2 e4c72a88 a830fb54 b9aea852 7887b5a6 bf2f85bb 22e878d0 c6916d06>; 
    ListDetails = <2cc64684 6520b473 d4bc4ae5 39f66fa0 0437788e ef1a0d91 1bdd7b52 86c0fbf2>; 
    Lists = <c2491da1 58622f56 64112d31 ba3e294a 1167e3f1 5427cd3a a56c1613 e2c0ee8a>; 
}; 
NSStoreModelVersionHashesVersion = 3; 
NSStoreModelVersionIdentifiers =  (
    "" 
); 
NSStoreType = SQLite; 
NSStoreUUID = "F84E0B5C-F83B-48ED-9043-5F9B6752FCA4"; 
"_NSAutoVacuumLevel" = 2; 
}, reason=The model used to open the store is incompatible with the one used to create the store}]) 

Я попытался решения, размещенные на этом сайте (например, удаление приложения из симулятора, чистой & сборки, Reset «Содержание & настройки» в тренажере), но ни один не работает в моем случае.

Заранее спасибо

ответ

0

В программировании IOS, каждая программа устанавливается в песочнице это означает, что они являются независимыми. Приложение не может получить доступ к данным из другого приложения, если другое приложение не разрешает такие действия.

В вашем случае есть более простой способ: preload данные. Вы можете хранить свои данные в настройках по умолчанию пользователя. При запуске приложения вы проверяете, нет ли данных по умолчанию пользователя. Если да, загрузите данные по умолчанию для пользователя (preload). Затем в будущем, поскольку есть данные по умолчанию пользователя, не загружайте снова.

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