iphone:Core Data:Where does a Managed Object Context Come From?

Where a managed object context comes from is entirely application-dependent. In a Cocoa document-based application using NSPersistentDocument, the persistent document typically creates the context, and gives you access to it through the managedObjectContext method.

In a single-window application, if you create your project using the standard project assistant, the application delegate (the instance of the AppDelegate class) again creates the context, and gives you access to it through the managedObjectContext method. In this case, however, the code to create the context (and the rest of the Core Data stack) is explicit. It is written for you automatically as part of the template.

from core Data FQA: http://developer.apple.com/library/mac/#documentation/cocoa/conceptual/coredata/Articles/cdFAQ.html#//apple_ref/doc/uid/TP40001802-CJBDBHCB

    // 指定存储数据文件
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDirectory, YES);
    NSString *documentsDirectory = [paths lastObject];
    NSString *persistentStorePath = [documentsDirectory stringByAppendingPathComponent:@"Model.sqlite"];
    //创建托管对象模型
    NSManagedObjectModel *managedObjectModel = [NSManagedObjectModel mergedModelFromBundles:nil];
    //创建持久化存储协调器,并使用SQLite数据库做持久化存储
    NSURL *storeUrl = [NSURL fileURLWithPath:persistentStorePath];
    NSPersistentStoreCoordinator *persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc]
                                                                initWithManagedObjectModel:managedObjectModel];
    NSError *error = nil;
    NSPersistentStore *persistentStore = [persistentStoreCoordinator 
                                          addPersistentStoreWithType:NSSQLiteStoreType
                                          configuration:nil
                                          URL:storeUrl
                                          options:nil
                                          error:&error];

    //创建托管对象上下文
    NSManagedObjectContext *managedObjectContext = [[NSManagedObjectContext alloc]init];
    [managedObjectContext setPersistentStoreCoordinator:persistentStoreCoordinator];
    
    self.context = managedObjectContext;

http://www.cnblogs.com/mybkn/articles/2472881.html

原文地址:https://www.cnblogs.com/mybkn/p/2472861.html