Core Data Migration: How to delete the Core Data stack?

后端 未结 2 2168
忘掉有多难
忘掉有多难 2021-02-13 21:50

My plan is to delete the old Core Data stack (the NSManagedObjectModel .momd file & the NSPersistentStore .sqlite file) b

2条回答
  •  不要未来只要你来
    2021-02-13 22:30

    It is a perfectly valid thing to do if your app requires internet access anyway. Otherwise users may be left with an empty data set (you delete the old database when you find it's incompatible with the current model, but you cannot re-populate it without access to the server).

    Technically, that's a trivial thing to do. When you set up the NSPersistentStoreCoordinator:

    NSURL *storeURL = ...;
    NSManagedObjectModel *managedObjectModel = ...;
    NSError *error = nil;
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel: managedObjectModel];
    
    // Check if we already have a persistent store
    if ( [[NSFileManager defaultManager] fileExistsAtPath: [storeURL path]] ) {
        NSDictionary *existingPersistentStoreMetadata = [NSPersistentStoreCoordinator metadataForPersistentStoreOfType: NSSQLiteStoreType URL: storeURL error: &error];
        if ( !existingPersistentStoreMetadata ) {
            // Something *really* bad has happened to the persistent store
            [NSException raise: NSInternalInconsistencyException format: @"Failed to read metadata for persistent store %@: %@", storeURL, error];
        }
    
        if ( ![managedObjectModel isConfiguration: nil compatibleWithStoreMetadata: existingPersistentStoreMetadata] ) {
            if ( ![[NSFileManager defaultManager] removeItemAtURL: storeURL error: &error] )
                NSLog(@"*** Could not delete persistent store, %@", error);
        } // else the existing persistent store is compatible with the current model - nice!
    } // else no database file yet
    
    [_persistentStoreCoordinator addPersistentStoreWithType: NSSQLiteStoreType 
                                              configuration: nil 
                                                        URL: storeURL 
                                                    options: nil 
                                                      error: &error];
    

提交回复
热议问题