@synchronized 在静态方法中

发布于 2024-08-01 20:49:58 字数 309 浏览 4 评论 0原文

在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

书信已泛黄 2024-08-08 20:49:58

类(静态)方法内部的 self 引用类对象。

self inside of a class (static) method refers to the class object.

鸠书 2024-08-08 20:49:58

有了上面的答案,只要记住,如果一个线程使用@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.

a√萤火虫的光℡ 2024-08-08 20:49:58

在 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)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文