當我向核心數據模型添加新屬性時,我希望使我的應用程序能夠進行自動的輕量級遷移。在Apple的指南中,這是我可以找到的關于該主題的唯一信息:自動輕量級遷移要請求自動輕量級遷移,您可以在addPersistentStoreWithType:configuration:URL:options:error:中傳遞的選項字典中設置適當的標志。您需要將與NSMigratePersistentStoresAutomaticallyOption和NSInferMappingModelAutomaticallyOption鍵對應的值設置為YES:NSError *error;NSURL *storeURL = <#The URL of a persistent store#>;NSPersistentStoreCoordinator *psc = <#The coordinator#>;NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];if (![psc addPersistentStoreWithType:<#Store type#> configuration:<#Configuration or nil#> URL:storeURL options:options error:&error]) { // Handle the error.}我NSPersistentStoreCoordinator是這樣初始化的:- (NSPersistentStoreCoordinator *)persistentStoreCoordinator { if (persistentStoreCoordinator != nil) { return persistentStoreCoordinator; } NSURL *storeUrl = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] stringByAppendingPathComponent: @"FC.sqlite"]]; NSError *error = nil; persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]]; if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:nil error:&error]) { NSLog(@"Unresolved error %@, %@", error, [error userInfo]); abort(); } return persistentStoreCoordinator;}我在查看應該在哪里以及如何添加Apple代碼以使自動輕量級遷移正常工作時遇到麻煩?
3 回答

躍然一笑
TA貢獻1826條經驗 獲得超6個贊
起初,上述解決方案對我不起作用。返回的managedObjectModel為0x0。我認為這是因為我重命名了不同模型文件的文件名。如果您按照上述說明進行操作,那么這一切都將起作用。
但是,如果您確實更改了模型文件名,則可以手動選擇“當前”模型文件:假設您的原始模型文件是MYMODEL.xcdatamodel,在執行上方的添加模型步驟后將變為目錄MY.xcdatamodeld,而在該目錄下面MYMODEL.xcdatamodel和MYMODEL 2.xcdatamodel將新模型文件重命名為所需的名稱,例如,假設您刪除了MYMODEL2.xcdatamodel的空間并編輯其內容。現在在上面的代碼中
NSString *path = [mainBundle pathForResource:@"MYMODEL2" ofType:@"mom" inDirectory:@"MYMODEL.momd"];
- 3 回答
- 0 關注
- 483 瀏覽
添加回答
舉報
0/150
提交
取消