Does @synchronized(self) create a block where the self prefix is unecessary on properties?

endo.anaconda picture endo.anaconda · Jan 11, 2011 · Viewed 24.9k times · Source

I have read something in some foreign code and I want to check my assumption:

@synchronized(self) is used to get rid of the self prefix when setting a property.

So in my example below, I'm setting the strText of the instance, not just a local variable, right?

- (void)myfunction{
    NSString * strText = @"var in function";
    @synchronized(self)
    {
         strText = @"var class (self.strText)";
    }

}

Answer

Tirth picture Tirth · Jan 11, 2011

Please read this Documentation

The @synchronized() directive locks a section of code for use by a single thread. Other threads are blocked until the thread exits the protected code—that is, when execution continues past the last statement in the @synchronized() block.

The @synchronized() directive takes as its only argument any Objective-C object, including self.

As Massimo Cafaro pointed out: "It’s safest to create all the mutual exclusion objects before the application becomes multithreaded, to avoid race conditions."