美文网首页
CoreData 添加新字段

CoreData 添加新字段

作者: 不言弃zxf | 来源:发表于2020-12-25 14:42 被阅读0次

给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 添加新字段

      本文链接:https://www.haomeiwen.com/subject/hlzbnktx.html