@synchronized 在静态方法中
在 Objective-C 中,您可以使用 @synchronized
构造将块声明为在某个对象上同步。 它看起来像这样:
@synchronized (self) {
// Do something useful
}
但是,我很好奇当你有一个静态方法时 self
到底指的是什么(+
而不是 -
>)。 我尝试查看苹果文档,他们暗示这是可以的,但并没有真正解释它。 我知道它有效,我只是好奇它意味着什么。
In Objective-C, you can declare a block as being synchronized on some object by using the @synchronized
construct. It would look something like this:
@synchronized (self) {
// Do something useful
}
However, I'm curious what exactly self
is referring to when you have a static method (+
instead of -
). I tried looking through the Apple docs, and they allude to it being OK, but don't really explain it. I know it works, I'm just curious what it means.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
类(静态)方法内部的
self
引用类对象。self
inside of a class (static) method refers to the class object.有了上面的答案,只要记住,如果一个线程使用@synchronized(self)调用实例方法,而另一个线程使用@synchronized(self)调用类方法,则两个调用之间不会发生同步,因为它们是使用不同的对象进行同步。
With the answers above, just keep in mind that if one thread calls an instance method using @synchronized (self), and another thread calls a class method using @synchronized (self), no synchronisation will happen between the two calls, because they are using different objects for synchronisation.
在 Objective-C 中,
self
由上下文决定。 在实例方法中,这将是被调用的实例。 在静态方法中,它将是类对象本身(即实例方法中[self class]
的结果)In Objective-C
self
is determined by context. In an instance method, that would be the instance being called. In a static method, it would be the class object itself (i.e. the result of[self class]
in an instance method)