Itay
Itay

Reputation: 1669

@synchronized in a static method

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.

Upvotes: 17

Views: 6105

Answers (3)

gnasher729
gnasher729

Reputation: 52538

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.

Upvotes: 0

Aviad Ben Dov
Aviad Ben Dov

Reputation: 6409

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)

Upvotes: 13

Wevah
Wevah

Reputation: 28242

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

Upvotes: 29

Related Questions