Created
August 8, 2017 03:30
-
-
Save Koze/17ef1c736a8a14edd116780ecaf9ae29 to your computer and use it in GitHub Desktop.
Change PersistentContainer URL dynamically.
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
#import <UIKit/UIKit.h> | |
#import <CoreData/CoreData.h> | |
@interface AppDelegate : UIResponder <UIApplicationDelegate> | |
@property (strong, nonatomic) UIWindow *window; | |
@property (readonly, strong) NSPersistentContainer *persistentContainer; | |
@property (nonatomic) NSURL *databaseURL; | |
- (void)saveContext; | |
@end |
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
#import "AppDelegate.h" | |
@implementation AppDelegate | |
#pragma mark - Core Data stack | |
@synthesize persistentContainer = _persistentContainer; | |
- (NSPersistentContainer *)persistentContainer { | |
@synchronized (self) { | |
if (_persistentContainer == nil) { | |
_persistentContainer = [[NSPersistentContainer alloc] initWithName:@"AppName"]; | |
if (self.databaseURL) { | |
NSPersistentStoreDescription *storeDescription = _persistentContainer.persistentStoreDescriptions.firstObject; | |
storeDescription.URL = self.databaseURL; | |
} | |
[_persistentContainer loadPersistentStoresWithCompletionHandler:^(NSPersistentStoreDescription *storeDescription, NSError *error) { | |
if (error != nil) { | |
NSLog(@"Unresolved error %@, %@", error, error.userInfo); | |
abort(); | |
} | |
}]; | |
} | |
} | |
return _persistentContainer; | |
} | |
- (void)setDatabaseURL:(NSURL *)databaseURL | |
{ | |
_databaseURL = databaseURL; | |
_persistentContainer = nil; | |
} | |
#pragma mark - Core Data Saving support | |
- (void)saveContext { | |
NSManagedObjectContext *context = self.persistentContainer.viewContext; | |
NSError *error = nil; | |
if ([context hasChanges] && ![context save:&error]) { | |
NSLog(@"Unresolved error %@, %@", error, error.userInfo); | |
abort(); | |
} | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment