Live data from Hacker News

Synchronizing class methods in Objective-C

vombat.tumblr.com

1–10 of 11 posts

Re: Synchronizing class methods in Objective-C

#2
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.

Re: Synchronizing class methods in Objective-C

#5

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

Yes in class methods self is the Class object, so the Class is used as the locking token:

> The object passed to the @synchronized directive is a unique identifier used to distinguish the protected block

Re: Synchronizing class methods in Objective-C

#8

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

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().

Re: Synchronizing class methods in Objective-C

#9

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

> I was under the impression it was the Class?

It is the class. But it's not the class in which the method is defined it's the class from which it is called.

So in one case it's the superclass and in the other case it's the subclass.

Re: Synchronizing class methods in Objective-C

#10
post #6

Why do you need to synchronize class methods? Global state mutation?

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

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...

Post reply on HN