牛骨文教育服务平台(让学习变的简单)
博文笔记

iOS 使用CoreData时该注意的问题之一

创建时间:2017-06-12 投稿人: 浏览次数:497

出现过的问题:在使用CoreData做数据缓存的时候,在Model里面增加了两个字段(Attribute),运行直接崩了。

其实,不仅仅是在Model里面增加字段,包括对数据库表(Entity)或者表中的字段(Attribute)直接进行了增删改的操作,都会崩了。

解决方法:

  (1)选中你的model.xcdatamodeld文件,选择菜单editor->Add Model Version  比如取名:model2.xcdatamodel

  (2)设置当前版本 

   选择上级model.xcdatamodeld ,在inspector中的Versioned Core Data Model选择Current模版为model2

  (3)修改新数据模型model2,在新的文件上添加字段及表

  (4)把原来的(绿色部分代码)改为下面的

 

增删改之前: [store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:storeUrl options:nil error:nil];

  //添加字段之后要这么写

 

增删改之后: NSDictionary *optionsDictionary = [NSDictionarydictionaryWithObjectsAndKeys:[NSNumbernumberWithBool:YES],

                                           NSMigratePersistentStoresAutomaticallyOption, [NSNumbernumberWithBool:YES],

                                           NSInferMappingModelAutomaticallyOption,nil];

        

 if (![storeaddPersistentStoreWithType:NSSQLiteStoreType

                                 configuration:nil

                                           URL:[NSURLfileURLWithPath:storeUrl

                                       options:optionsDictionary

                                         error:nil]) {

            

            NSLog(@"failed to add persistent store with type to persistent store coordinator");

            

        }




声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。