【问题标题】:creating a nsmanagedcontext in IOS 9 and below在 IOS 9 及更低版本中创建 nsmanagedcontext
【发布时间】:2018-08-16 09:51:05
【问题描述】:

在 IOS 10 中,创建 NSManagedObjectContext 和 nsmanagedObject 如下:

 NSManagedObjectContext *context =   ((AppDelegate*)[[UIApplication sharedApplication] delegate]).persistentContainer.viewContext;
    NSManagedObject *object = [NSEntityDescription insertNewObjectForEntityForName:@"Leads"                                  inManagedObjectContext:context];

但是,在 ios 9 及更高版本中,没有 presistentContainer,那么如何在 IOS 9 中创建 NSManagedObjectContext?我尝试了以下方法,但没有奏效,它返回 nil:

- (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;
}

【问题讨论】:

标签: objective-c core-data nsmanagedobjectcontext


【解决方案1】:

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

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

  • NSPrivateQueueConcurrencyType
  • NSMainQueueConcurrencyType

所以如下:

_managedObjectContext = [[NSManagedObjectContext alloc] init];

应该变成:

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

参考:https://developer.apple.com/documentation/coredata/nsmanagedobjectcontext#//apple_ref/c/tdef/NSManagedObjectContextConcurrencyType

【讨论】:

    猜你喜欢
    • 2017-01-17
    • 2016-09-27
    • 1970-01-01
    • 2017-01-24
    • 2019-11-12
    • 2021-03-07
    • 1970-01-01
    • 2019-10-20
    • 1970-01-01
    相关资源
    最近更新 更多