美文网首页
CoreData 添加新字段[转]

CoreData 添加新字段[转]

作者: 陈大帅 | 来源:发表于2019-10-26 10:52 被阅读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 = [NSDictionary dictionaryWithObjectsAndKeys:@YES,NSInferMappingModelAutomaticallyOption, @YES,NSMigratePersistentStoresAutomaticallyOption, nil];
    
        if (_persistentStoreCoordinator != nil) {
    
            return _persistentStoreCoordinator;
    
        }
    
        // Create the coordinator and store
    
        _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    
        NSURL *storeURL = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask].firstObject URLByAppendingPathComponent:@"DemoCoreData.sqlite"];
    
        NSError *error = nil;
    
        NSString *failureReason = @"There was an error creating or loading the application's saved data.";
    
        if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error]) {
    
            // Report any error we got.
    
            NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    
            dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
    
            dict[NSLocalizedFailureReasonErrorKey] = failureReason;
    
            dict[NSUnderlyingErrorKey] = error;
    
            error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN"code:9999 userInfo: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/xquyvctx.html