Question

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.

Was it helpful?

Solution

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

OTHER TIPS

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)

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top