Objective c 在IOS 9及以下版本中创建nsmanagedcontext

Objective c 在IOS 9及以下版本中创建nsmanagedcontext,objective-c,core-data,nsmanagedobjectcontext,Objective C,Core Data,Nsmanagedobjectcontext,在IOS 10中,创建nsmanagedObject上下文和nsmanagedObject的步骤如下: NSManagedObjectContext *context = ((AppDelegate*)[[UIApplication sharedApplication] delegate]).persistentContainer.viewContext; NSManagedObject *object = [NSEntityDescription insertNewObjectF

在IOS 10中,创建nsmanagedObject上下文和nsmanagedObject的步骤如下:

 NSManagedObjectContext *context =   ((AppDelegate*)[[UIApplication sharedApplication] delegate]).persistentContainer.viewContext;
    NSManagedObject *object = [NSEntityDescription insertNewObjectForEntityForName:@"Leads"                                  inManagedObjectContext:context];
但是,在ios 9及更高版本中,没有presistentContainer,因此如何在ios 9中创建NSManagedObjectContext?我尝试了以下方法,但无效,结果为零:

- (NSManagedObjectContext *)managedObjectContext {
    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }

    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (!coordinator) {
        return nil;
    }
    _managedObjectContext = [[NSManagedObjectContext alloc] init];
    [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    return _managedObjectContext;
}

在iOS 9中,NSManagedObjectContext的实例化更改为指定此对象的并发类型

这意味着我们现在必须选择初始化托管对象上下文的线程:主队列,或者我们创建的特殊后台队列。我们的选择是:

  • NSPrivateQueueConcurrencyType
  • NSMainQueueConcurrencyType
因此,下文:

_managedObjectContext = [[NSManagedObjectContext alloc] init];
应成为:

_managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
参考: