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;

}

 

转载于:https://www.cnblogs.com/zhujin/p/5500759.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值