Home:ALL Converter>Core Data initialization

Core Data initialization

Ask Time:2016-09-19T00:47:20         Author:Smart Home

Json Formatter

Looking at Apple documentation, I see that they are recommending removing Core Data initialization code out of AppDelegate. Their approach is below.

What I don't understand are the following

  1. The sentence below in the documentation. How is there a callback to app delegate? I don't see one in the code snippets below. Is it something they want us to add.

By initializing a separate controller object with a completion block, you have moved the Core Data stack out of the application delegate, but you still allow a callback to the application delegate so that the user interface can know when to begin requesting data.

  1. AppDelegate calls init of DataController and this in turn this calls initializeCoreData. But initializeCoreData sets up the persistent store co-ordinator in a background thread. Which means that if we transition to the application's first view and its view controller requests data from core-data, things are not yet set up. Won't this be an issue? Does this mean they want us to show a different launch screen & register for a callback that tells us that CoreData initialization is done before moving to actual first application view.

AppDelegate code in documentation

-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    [self setDataController:[[DataController alloc] init];
    // Basic User Interface initialization
    return YES;
}

DataController code in documentation

@interface MyDataController : NSObject

@property (strong) NSManagedObjectContext *managedObjectContext;

-(void)initializeCoreData;

@end

@implementation MyDataController

-(id)init {

    self = [super init];
    if (!self) return nil;

    [self initializeCoreData];

    return self;
}

- (void)initializeCoreData {

    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"DataModel" withExtension:@"momd"];
    NSManagedObjectModel *mom = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    NSAssert(mom != nil, @"Error initializing Managed Object Model");

    NSPersistentStoreCoordinator *psc = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:mom];
    NSManagedObjectContext *moc = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
    [moc setPersistentStoreCoordinator:psc];
    [self setManagedObjectContext:moc];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSURL *documentsURL = [[fileManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
    NSURL *storeURL = [documentsURL URLByAppendingPathComponent:@"DataModel.sqlite"];

    dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void) {
        NSError *error = nil;
        NSPersistentStoreCoordinator *psc = [[self managedObjectContext] persistentStoreCoordinator];
        NSPersistentStore *store = [psc addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error];
        NSAssert(store != nil, @"Error initializing PSC: %@\n%@", [error localizedDescription], [error userInfo]);
    });
}

Author:Smart Home,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/39560195/core-data-initialization
Michael Dautermann :

1)\n\nIn the Core Data programming guide you're looking at, the authors are taking Core Data out of the App Delegate (which tends to get cluttered up with a lot of extra code that developers really should split out into separate objects). \n\nThe rest of the documentation explains:\n\n\n It is recommended that the Core Data stack be created within its own\n top-level controller object and that the application delegate\n initialize that controller object and hold a reference to it. This\n action will promote the consolidation of the Core Data code within its\n own controller and keep the application delegate relatively clean.\n\n\nAlso:\n\n\n assign the adding of the persistent store (NSPersistentStore) to the\n persistent store coordinator (NSPersistentStoreCoordinator) to a\n background queue. That action can take an unknown amount of time, and\n performing it on the main queue can block the user interface, possibly\n causing the application to terminate.\n \n Once the persistent store has been added to the persistent store\n coordinator, you can then call back onto the main queue and request\n that the user interface be completed and displayed to the user\n\n\nSo yes, CoreData might not necessarily be completely up by the time your first view controller is displayed, but if you have an observer looking for a NSNotification from that background queue, you can tell your UI when CoreData is ready to be relied upon.\n\n2)\n\n[DataController init] won't return a DataController object until initializeCoreData returns, so your UI will not display until after didFinishLaunchingWithOptions returns and you should already have a DataController object. ",
2016-09-18T16:59:54
yy