开发者

how to make an iPhone app tolerant of a CoreData schema change

I have an app that uses the CoreData APIs extensively. I'm developing an updated version that adds a few fields to an entity. My app crashes upon load (unless if I blow away the private storage and start again) because of the schema changes.

The problem is when customers 开发者_运维知识库upgrade to the new version, I wouldn't mind running an upgrade procedure on their data the first time the app loads, but I can't even get it to load because CoreData doesn't like that the schema changes.

Is there any way to sort of tell CoreData "Its ok.. don't worry about the schema change"? Because I have only added fields and haven't renamed or deleted anything.


You should probably get a copy of Marcus Zarra's Core Data book and read up on migration (Ch. 5). But, failing that, there are some basics that are good to know. First, you need both your old model (schema) and your new model in your updated app. Second, you need to make sure that the new model is tagged as being the "current model". Third, you need to make sure that you create your NSPersistentStoreCoordinator in such a way that it automatically maps from existing model (as loaded from disk) to new model.

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
    {
    if (persistentStoreCoordinator)
        return persistentStoreCoordinator;

    NSURL *storeUrl = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] stringByAppendingPathComponent: @"MyDataStore.sqlite"]];

    NSError *error = nil;
    persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel: [self managedObjectModel]];

    // Use mapping model
    NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
                             [NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, nil];


    if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType 
                                configuration:nil
                                URL:storeUrl
                                options:options
                                error:&error])
        {
        [NSApp presentError:error];
        }
    return persistentStoreCoordinator;
    }

Update Your old model in your new app needs to be exactly the same as the model in your old app. If you are unsure that this is the case, then there are some steps that you can take to make sure. The way I do it is a bit involved - but I will outline it if/when you think that that would be helpful.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜