'Can only use -performBlock: on an NSManagedObjectContext that was created with a queue.' 错误

'Can only use -performBlock: on an NSManagedObjectContext that was created with a queue.' Error

我用NSManagedObjectContext performBlock{} 但, 我的应用总是在这里崩溃

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Can only use -performBlock: on an NSManagedObjectContext that was created with a queue.'

如何知道关于 NSManagedObjectContext 的正确线程。 创建 NSManagedObjectContext 代码在这里

Person *aPerson = (Person *)[NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:[CoreDataManager sharedInstance].managedObjectContext];

请多提意见

像这样创建您的 ManagedObjectContext

NSManagedObjectContext *moc = [[NSManagedObjectContext alloc]
                     initWithConcurrencyType:NSMainQueueConcurrencyType];

NSMainQueueConcurrencyType 创建一个与主调度队列相关联的上下文,从而与主线程相关联。您可以将这样的上下文 link 用于主线程上 运行 所需的对象,例如 UI 元素。

NSPrivateQueueConcurrencyType 创建并管理一个要在其上运行的私有调度队列。您必须使用新方法 performBlock: 或 performBlockAndWait:。然后上下文将在它自己的私有队列上执行传递的块。

最后,NSConfinementConcurrencyType 是默认类型,只能在创建它的线程内使用。

该错误并不是说您使用了错误的线程。它说您只能在使用队列创建的上下文中使用 -performBlock:。如 NSManagedObjectContext/Concurrency 的 class 参考中所述,这只是使用选项 NSPrivateQueueConcurrencyTypeNSMainQueueConcurrencyType 集之一创建的上下文。

You use contexts using the queue-based concurrency types in conjunction with performBlock: and performBlockAndWait:.