關於coredata 網上的相關資料比較少,大部分是基本用法。於是便找到蘋果官方文檔進行深入學習。
分享一下心得,如果用了coredata 必須懂得 coredata Migration,否則app版本更新 core data model schema 變化很大可能導致持久化coredata 出錯,程式崩潰。
以下幾種情況 可以簡單的用 Lightweight Migration 遷移資料到新版本Model, 如下。
NSDictionary *options = [NSDictionarydictionaryWithObjectsAndKeys:[NSNumbernumberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, [NSNumbernumberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];
_persistentStoreCoordinator = [[NSPersistentStoreCoordinatoralloc] initWithManagedObjectModel:[selfmanagedObjectModel]];
if (![_persistentStoreCoordinatoraddPersistentStoreWithType:NSSQLiteStoreTypeconfiguration:nilURL:storeURL options:options error:&error])
//其他代碼
--------------幾種情況概括如下--------------------
1,Simple addition of a new attribute.(為某個Entity 添加屬性)
2,Removal of an attribute.(為某個Entity 刪除屬性)
3,A non-optional attribute becoming optional.
4,An optional attribute becoming non-optional, and defining a default value.
5,Renaming an entity or property.
<注意>You cannot, however, merge entity hierarchies; if two existing entities do not share a common parent in the source, they cannot share a common parent in the destination。這種情況不能用輕量遷移。
官方文檔:
https://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/CoreDataVersioning/Articles/vmLightweightMigration.html#//apple_ref/doc/uid/TP40004399-CH4-SW1
下篇 《 core data model mapping 》