我看了一些国外的代码,想验证一下我的假设:
@synchronized(self)
用于在设置属性时去掉 self
前缀。
所以在我下面的示例中,我正在设置实例的 strText
,而不仅仅是局部变量,对吧?
- (void)myfunction{
NSString * strText = @"var in function";
@synchronized(self)
{
strText = @"var class (self.strText)";
}
}
最佳答案
请阅读此Documentation
The
@synchronized()
directive locks a section of code for use by a single thread. Other threads are blocked until the thread exits the protected code—that is, when execution continues past the last statement in the@synchronized()
block.The
@synchronized()
directive takes as its only argument any Objective-C object, includingself
.
作为Massimo Cafaro pointed out : “最安全的做法是在应用程序变为多线程之前创建所有互斥对象,以避免竞争条件。”
关于objective-c - @synchronized(self) 是否创建一个 block ,其中 self 前缀在属性上是不必要的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4654487/