CoreData 添加新字段

给CoreData添加新属性,就是给数据库加新字段,那么必须要进行数据库版本升级及CoreData数据迁移;

具体操作是

1.选择DemoCoreData.xcdatamodeld 文件,Editor ->Add Model Version ,输入新的版本名字;

2.在右侧的文件查看器窗口 的Model Version   current 设置当前最新的版本名字;

3.在新数据模型的文件上添加字段,记得在类文件里也要添加上你添加的新字段,可以删除原来的类文件,重新生成manageobject类。

4.代码中加入 数据迁移的配置选项:

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {

    //

The persistent store coordinator for the application. This

implementation creates and returns a coordinator, having added the store

for the application to it.

    //设置CoreData迁移配置

    NSDictionary *options = [NSDictionarydictionaryWithObjectsAndKeys:@YES,NSInferMappingModelAutomaticallyOption, @YES,NSMigratePersistentStoresAutomaticallyOption, nil];


    if (_persistentStoreCoordinator != nil) {

        return_persistentStoreCoordinator;

    }


    // Create the coordinator and store


    _persistentStoreCoordinator = [[NSPersistentStoreCoordinatoralloc] initWithManagedObjectModel:[selfmanagedObjectModel]];

    NSURL *storeURL = [[selfapplicationDocumentsDirectory] URLByAppendingPathComponent:@"DemoCoreData.sqlite"];

    NSError *error = nil;

    NSString *failureReason = @"There was an error creating or loading the application's saved data.";

    if (![_persistentStoreCoordinatoraddPersistentStoreWithType:NSSQLiteStoreTypeconfiguration:nilURL:storeURL options:options error:&error]) {

        // Report any error we got.

        NSMutableDictionary *dict = [NSMutableDictionarydictionary];

        dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";

        dict[NSLocalizedFailureReasonErrorKey] = failureReason;

        dict[NSUnderlyingErrorKey] = error;

        error = [NSErrorerrorWithDomain:@"YOUR_ERROR_DOMAIN"code:9999userInfo: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();

    }


    return_persistentStoreCoordinator;

}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 实现收藏有很多方式,我在自己练习的项目中用CoreData实现了一下收藏功能,注释很少,算是自己做的一个笔记。首先...
    HeartPower阅读 6,863评论 18 13
  • 1 CoreData运行机制 1.1 CoreData总体架构 1.1.1 CoreData架构图 CoreDat...
    Kevin_Junbaozi阅读 9,209评论 2 7
  • CoreData数据持久化框架是Cocoa API的一部分,首次在iOS5版本中出现,它允许按照实体-属性-值模式...
    Zcocoa阅读 3,192评论 0 0
  • 相信大家开发的时候都用过coredata,用来保存数据挺方便的。只是问题是,突然发现,如果最开始创建项目的时候没...
    saintPN阅读 4,440评论 0 0
  • 1.简介 1)coreData提供了对象持久化管理,不需要关心数据的内部存储,只需要关心对象的增删查改. FM...
    _skye阅读 10,019评论 3 26