从 NSOperation 中删除主线程中的 NSManagedObject
当从 NSOperation 在主线程上的 NSManagedObjectContext 上调用 deleteObject:
时,我是否还需要引用主线程上的 objectID?目前,我正在通过以下方式从 NSOperation 中删除主线程中的 NSManagedObject...
NSManagedObjectContext *mainContext = [[[UIApplication sharedApplication] delegate] managedObjectContext];
- (void)deleteObject:(NSManagedObjectID *)objectID
{
// Delete on main context on the main thread
[mainContext performSelectorOnMainThread:@selector(deleteObject:)
withObject:[mainContext objectWithID:objectID]
waitUntilDone:YES];
}
它正在工作,但我想确保它稍后不会在我身上爆炸。我不确定的是 [mainContext objectWithID:objectID]
是否从 NSOperation 引用 NSManagedObjectContext,或者因为该方法调用位于 performSelectorOnMainThread:withObject:waitUntilDone: 都是在主线程执行的吗?
When invoking deleteObject:
on an NSManagedObjectContext on the main thread from an NSOperation, do I also need to reference the objectID on the main thread? Currently I am deleting an NSManagedObject in the main thread from an NSOperation in the following way...
NSManagedObjectContext *mainContext = [[[UIApplication sharedApplication] delegate] managedObjectContext];
- (void)deleteObject:(NSManagedObjectID *)objectID
{
// Delete on main context on the main thread
[mainContext performSelectorOnMainThread:@selector(deleteObject:)
withObject:[mainContext objectWithID:objectID]
waitUntilDone:YES];
}
It's working but I want to make sure it doesn't blow up on me later. The thing I'm not sure about is if [mainContext objectWithID:objectID]
is referencing the NSManagedObjectContext from the NSOperation, or since that method invokation is within the performSelectorOnMainThread:withObject:waitUntilDone:
is it all being performed on the main thread?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
NSManagedObjectID 的实例可以安全地跨线程边界共享。但是,您对 mainContext objectWithID: 的调用将获取实际对象,这不是线程安全的。
您可能应该做的是将其包装在可以在主队列上执行的选择器或块中。
或者,您可以让主线程队列为您执行此操作:
当然,所有这些都引出了一个问题,为什么您要尝试从另一个线程上的 NSOperation 实例中删除基于主线程的上下文中的对象?
Instances of NSManagedObjectID are safe to share across thread boundaries. However your call to mainContext objectWithID: will get the actual object, which is not thread safe.
What you should probably do is wrap this in a selector or block which can be performed on the main queue.
Alternatively you can have your main thread queue do this for you:
Of course, all of this begs the question, why are you trying to delete objects in a main-thread based context from an instance of NSOperation on another thread?