什么时候安全使用 - [NSManagedObjectContext lock]? [英] When is it safe to use -[NSManagedObjectContext lock]?

查看:289
本文介绍了什么时候安全使用 - [NSManagedObjectContext lock]?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道你应该遵守CoreData的线程限制规则,但是是否可以安全地使用 - [NSManagedObjectContext lock] 和朋友?我知道访问 NSManagedObject 属性可以触发隐式 NSManagedObjectContext fetch如果 NSManagedObject 已卸载的属性,所以我假设你必须包装 NSManagedObject 属性访问 - [NSManagedObjectContext lock] - [NSManagedObjectContext unlock] 。我以为这是唯一的。是否有其他人?

I know that you should abide by CoreData's thread confinement rules in general, but is it ever safe to use -[NSManagedObjectContext lock] and friends? I know that accessing an NSManagedObject property can trigger an implicit NSManagedObjectContext fetch if the NSManagedObject has unloaded properties, so I assume you would have to wrap all NSManagedObject property accesses around -[NSManagedObjectContext lock] and -[NSManagedObjectContext unlock]. I thought this was the only gotcha. Are there others?

此答案的评论中, Marcus Zarra说,我误解了关于 -\ [NSManagedObjectContext lock\] 和朋友的文档:

In the comments of this answer, Marcus Zarra says that I'm misinterpreting the documentation about -\[NSManagedObjectContext lock\] and friends:


将此消息发送到受管对象上下文有助于框架
理解多线程
环境中的事务范围。最好使用NSManagedObjectContext的NSLocking的
实现,而不是使用单独的互斥对象。

Sending this message to a managed object context helps the framework to understand the scope of a transaction in a multi-threaded environment. It is preferable to use the NSManagedObjectContext’s implementation of NSLocking instead using of a separate mutex object.

意味着您可以使用其他锁来保护 NSManagedObjectContext 。这是真的吗?

Also, the above quote implies that you can use other locks to guard NSManagedObjectContext. Is this true?

我不担心这个问题的父/子上下文。

I'm not worried about parent/child contexts for this question.

推荐答案

在学术环境中,你能使用锁吗?是的。

In an academic setting, can you use locks? yes.

你应该在生产代码中使用它们吗?没有。为什么?因为第一次获得正确的几率是非常高的。在维护模式下正确运行会迅速接近零。

Should you ever use them in production code? no. Why? Because the odds of getting it right the first time are extra-ordinarily high. Getting it right in maintenance mode rapidly approaches zero.

使用锁访问Core Data只是要求麻烦。当你弄错了你丢失/损坏的数据。当你得到它正确,你甚至与线密封破碎。

Using locks to access Core Data is just asking for trouble. When you get it wrong you lose/corrupt data. When you get it right you are breaking even with thread confinement. It is a lose/lose gamble with nothing to gain.

最糟糕的部分是,根本没有办法知道你是否正确直到或除非你丢失数据。永远不值得承担风险。

The worst part is that there is virtually no way to know if you got it "right" until or unless you lose data. Never worth the risk.

我还要指向 Ben的回应,应该给你一些关于这个主题的不错的历史。

I would also point you to this response from Ben which should give you some nice history on this subject.

这篇关于什么时候安全使用 - [NSManagedObjectContext lock]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆