iOS CoreData简介及使用中的注意点
图1
如图1所示,CoreData将NSManagedObject的接口暴露给App,最终通过其save方法进行事务的保存。
图2
1,iOS中使用CoreData时,如果对数据库表(Entity)或者表中的字段(Attribute)进行了增删改的操作,可能会抛出NSInternalConsistencyException异常,需要创建新的模型版本,处理如下:
(1)选中你的mydata.xcdatamodeld文件,选择菜单editor->Add Model Version 比如取名:mydata2.xcdatamodel
(2)设置当前版本
选择上级mydata.xcdatamodeld ,在inspector中的Versioned Core Data Model选择Current模版为mydata2
(3)修改新数据模型mydata2,在新的文件上添加字段及表
(4)删除原来的类文件,重新生成下类。
(5)在appdelegate中,增加*optionsDictionary。
NSDictionary *optionsDictionary = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES],
NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES],
NSInferMappingModelAutomaticallyOption, nil];
if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType
configuration:nil
URL:storeUrl
options:optionsDictionary
error:&error]) {
2,如何删除versioned model。
由于在Xcode中无法删除xxx.xcdatamodeld下的versioned model,所以需要在Finder中拷贝xxx.xcdatamodeld未为xxx副本.xcdatamodeld,将其中不需要的model删除后,将Xcode中的原文件删除,将新的副本加入Xcode中。
3,CoreData在多线程中的使用
MOC并不能直接在子线程中使用,需要在主线程中创建MOC,将要在子线程中执行的内容写在peformBlock方法中。
关于CoreData多线程的方案有二层方案和三层方案:
具体可参考:http://blog.csdn.net/u014410695/article/details/48650965
代码可参考:asyncCoreDataWrapper-master
- 上一篇: CoreData并发操作模式简介
- 下一篇: CoreData的多线程存储(代码)