

Synchronizing class methods in Objective-C - MishraAnurag
http://vombat.tumblr.com/post/83074022251/synchronizing-around-a-class

======
WoodenChair
I think it's easy to forget that Objective-C has simple syntax for
synchronized code analogous to that of Java (although not quite as flexible as
Java's - we can't make a whole method synchronized simply by adding the
keyword to its declaration for example). A lot is made of Objective-C's
syntactical shortcomings, but little of its wins.

------
stickydink
So, what _is_ self inside a class method? I was under the impression it was
the Class?

~~~
marcomonteiro
self in that context would be the class. The issue he was facing is that in
subclasses, "self", would refer to a different class and therefore the lock
wouldn't apply. What he's pointing out is that he resolved that issue by
specifying the superclass explicitly.

Personally, if I had to ensure synchronous calls to a class variable, I'd
prefer to just restrict calls like this to a specific queue using
dispatch_sync().

------
tomlu
Why _do_ you need to synchronize class methods? Global state mutation?

~~~
chrisdevereux
Lazily instantiating a shared object is the obvious reason. Doesn't need to be
mutable.

~~~
jonhohle
dispatch_once(3)[0] can be used for lazy initialization without concern for
the calling class and without synchronizing on a shared object. This is
(likely) cheaper in most cases then entering a @synchronized block.

0 -
[https://developer.apple.com/library/mac/documentation/Darwin...](https://developer.apple.com/library/mac/documentation/Darwin/Reference/Manpages/man3/dispatch_once.3.html)

~~~
chrisdevereux
Yes. In general, either GCD or lower level atomic ops are a better choice for
thread-safety than @synchronized blocks. Just pointing out that there are
reasons other than global mutable state for wanting a critical section in a
class method.

