轻量级迁移失败时,如何编写自定义 NSEntityMigrationPolicy?

解读

在国内 iOS 面试中,Core Data 迁移是“必答题”。轻量级迁移(Lightweight Migration)只能处理“增删属性、重命名实体/属性、新增关系”等简单场景;一旦需要字段拆分、数据清洗、跨实体计算、旧值到新值的非线性映射,就必须走“重量级”迁移,而重量级迁移的核心就是自定义 NSEntityMigrationPolicy。面试官想确认三件事:

  1. 你是否真的踩过坑——知道轻量级失败的根本原因;
  2. 你是否能独立写出 Policy 子类并正确注入 Mapping Model;
  3. 你是否能在子类里安全地使用 Objective-C Runtime、线程、内存管理,保证迁移前后数据一致性。

知识点

  1. 迁移三件套:Versioned Model → Mapping Model → Migration Policy
  2. NSEntityMigrationPolicy 生命周期方法:
    • createDestinationInstances(forSource:sManager:)
    • createRelationships(forSource:destination:in:mapping:)
    • performCustomValidation(forMappingManager:error:)
  3. 属性值转换三大钩子:
    • value(forKey:key) 覆盖旧值读取
    • setValue(_:forKey:in:) 写入新值
    • func sourceInstance(forDestination:) 反向查找
  4. Objective-C Runtime 在迁移中的典型用法:
    • 动态创建 NSEntityDescription 避免硬编码
    • 用 class_addMethod 给 Policy 动态注入工具方法,减少子类膨胀
  5. 线程与内存:
    • Migration 跑在私有队列上下文,禁止触碰主线程 UI
    • ARC 下仍需注意“强引用循环”——Policy 持有 NSMigrationManager 会死锁
  6. 国内大厂灰度策略:
    • 在 performCustomValidation 里埋点,把失败样本上报到 APM(如阿里 SLS、腾讯 Bugly)
    • 对 10 w+ 数据表采用分页迁移,每 2 000 条手动 save: 一次,防止 OOM 被系统杀死

答案

步骤一:判定轻量级失败
在 NSPersistentStoreCoordinator 添加选项 NSMigratePersistentStoresAutomaticallyOption=YES、NSInferMappingModelAutomaticallyOption=YES 后,若 addPersistentStore 抛错 NSError 域为 NSCocoaErrorDomain 且 code 为 134140(持久化存储不兼容),即确认需自定义 Policy。

步骤二:新建 Mapping Model
Xcode → File → New → Mapping Model,选源版本和目标版本,生成 xxx.cdm 文件;在右侧面板把需要自定义的 Entity 的 “Mapping Type” 改为 “Custom”,在 “Custom Policy” 栏填入类名 XXUserMigrationPolicy1to2。

步骤三:编写 Policy 子类

// XXUserMigrationPolicy1to2.h
#import <CoreData/CoreData.h>
@interface XXUserMigrationPolicy1to2 : NSEntityMigrationPolicy
@end

// XXUserMigrationPolicy1to2.m
#import "XXUserMigrationPolicy1to2.h"
@implementation XXUserMigrationPolicy1to2

// 1. 创建目标对象
- (BOOL)createDestinationInstancesForSourceInstance:(NSManagedObject *)sInstance
                                      entityMapping:(NSEntityMapping *)mapping
                                            manager:(NSMigrationManager *)manager
                                              error:(NSError **)error {
    // 取出旧值
    NSString *oldFullName = [sInstance valueForKey:@"fullName"];
    // 自定义拆分规则
    NSArray *parts = [oldFullName componentsSeparatedByString:@" "];
    // 创建新对象
    NSManagedObject *newUser = [NSEntityDescription insertNewObjectForEntityForName:@"User"
                                                             inManagedObjectContext:[manager destinationContext]];
    [newUser setValue:parts.firstObject forKey:@"firstName"];
    [newUser setValue:parts.lastObject  forKey:@"lastName"];
    // 建立实例对应表,供后续关系迁移使用
    [manager associateSourceInstance:sInstance withDestinationInstance:newUser forEntityMapping:mapping];
    return YES;
}

// 2. 关系迁移
- (BOOL)createRelationshipsForDestinationInstance:(NSManagedObject *)dInstance
                                      entityMapping:(NSEntityMapping *)mapping
                                            manager:(NSMigrationManager *)manager
                                              error:(NSError **)error {
    // 通过 associate 表找到源对象
    NSManagedObject *sInstance = [manager sourceInstancesForEntityMappingNamed:mapping.name
                                                          destinationInstances:@[dInstance]].firstObject;
    // 旧 User 有一对多 Card,新模型把 Card 移到单独的 Wallet 实体
    NSSet *oldCards = [sInstance valueForKey:@"cards"];
    if (oldCards.count) {
        NSManagedObject *newWallet = [NSEntityDescription insertNewObjectForEntityForName:@"Wallet"
                                                                 inManagedObjectContext:[manager destinationContext]];
        [newWallet setValue:dInstance forKey:@"user"];
        NSMutableSet *newCards = [NSMutableSet set];
        for (NSManagedObject *oldCard in oldCards) {
            NSManagedObject *newCard = [manager destinationInstanceForEntityMappingName:@"CardToCard"
                                                                    sourceInstance:oldCard];
            if (newCard) [newCards addObject:newCard];
        }
        [newWallet setValue:newCards forKey:@"cards"];
    }
    return YES;
}

// 3. 数据验证与埋点
- (BOOL)performCustomValidationForMappingManager:(NSMigrationManager *)manager error:(NSError **)error {
    NSUInteger total = [[manager sourceContext] registeredObjects].count;
    if (total > 100000) {
        // 国内 App 常见灰度日志
        NSLog(@"[Migration] Large dataset detected, rows=%lu", (unsigned long)total);
    }
    return YES;
}
@end

步骤四:注入并触发
把 xxx.cdm 拖入主 Bundle;addPersistentStore 时不再设置 NSInferMappingModelAutomaticallyOption,而是手动加载:

NSURL *mappingURL = [[NSBundle mainBundle] URLForResource:@"xxx" withExtension:@"cdm"];
NSMappingModel *mapping = [[NSMappingModel alloc] initWithContentsOfURL:mappingURL];
NSMigrationManager *mgr = [[NSMigrationManager alloc] initWithSourceModel:srcModel destinationModel:dstModel];
BOOL ok = [mgr migrateStoreFromURL:srcStoreURL
                              type:NSSQLiteStoreType
                           options:nil
                  withMappingModel:mapping
                  toDestinationURL:dstStoreURL
                   destinationType:NSSQLiteStoreType
                destinationOptions:nil
                             error:&error];

步骤五:验证与回滚
在 performCustomValidation 里返回 NO 即可触发回滚;生产环境建议把旧数据库备份到 /Library/Caches/migration_backup.sqlite,迁移失败可提示用户“卸载重装”。

拓展思考

  1. 如果源模型里缺少唯一键,如何防止重复迁移?
    可在 Policy 里给目标实体增加 migrationUUID 属性,用 NSUUID 生成并写入,然后在外层记录到 NSUserDefaults,下次启动比对。

  2. 大型二进制字段(如 NSData *thumbnail)如何做到边迁移边清理?
    在 createDestinationInstancesForSourceInstance 里把二进制写到临时目录,迁移完成后统一发通知给业务层,由业务层在下次冷启时删除临时文件,避免一次性占用双倍存储。

  3. 国内审核政策要求“用户可拒绝升级”,如何做到后台下载新模型、延迟迁移?
    把 Mapping Model 和 Policy 打进 App 内,但在第一次启动只执行 NSLightweightMigrationOption,检测到需要 Policy 时弹窗提示“数据升级,预计 30 秒”,用户点击确认后才走重量级迁移;若用户拒绝,则保持只读旧库,新功能不可用。