Last active
August 29, 2015 14:26
-
-
Save kenthumphries/cf5ae5e85cb366d89626 to your computer and use it in GitHub Desktop.
Method to quickly perform a block using a temporary managed object context. Can be useful if you need to perform a few pre-migration optimisations to a database.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
typedef NSError *(^NSManagedObjectContextBlock)(NSManagedObjectContext *context); | |
+ (void)performBlock:(NSManagedObjectContextBlock)block withTemporaryManagedObjectContextFromDatabaseAtURL:(NSURL *)url withModelBundle:(NSBundle *)bundle | |
{ | |
NSParameterAssert(block); | |
if (!block) | |
{ | |
return; | |
} | |
NSDictionary *storeMetadata = [NSPersistentStoreCoordinator metadataForPersistentStoreOfType:NSSQLiteStoreType URL:url error:nil]; | |
NSManagedObjectModel *sourceModel = [NSManagedObjectModel mergedModelFromBundles:@[bundle] forStoreMetadata:storeMetadata]; | |
if (sourceModel) // If sourceModel cannot be found, cannot create a context | |
{ | |
@autoreleasepool { | |
// Create a temporary persistentStoreCoordinator based on source model | |
NSPersistentStoreCoordinator *temporaryStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:sourceModel]; | |
NSError *error; | |
[temporaryStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType | |
configuration:nil | |
URL:url | |
options:@{NSIgnorePersistentStoreVersioningOption:@YES} | |
error:&error]; | |
if (!error) | |
{ | |
NSManagedObjectContext *temporaryManagedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType: NSMainQueueConcurrencyType]; | |
temporaryManagedObjectContext.persistentStoreCoordinator = temporaryStoreCoordinator; | |
block(temporaryManagedObjectContext); | |
temporaryManagedObjectContext = nil; // Clean up to release any ownership of DB store | |
} | |
temporaryStoreCoordinator = nil; // clean up to release any ownership of DB store | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment