Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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)";     }  } 
like image 417
endo.anaconda Avatar asked Jan 11 '11 05:01

endo.anaconda


People also ask

What is @synchronized self?

@synchronized(self) is used to get rid of the self. prefix.

What is @synchronized Objective C?

The @synchronized directive is a convenient way to create mutex locks on the fly in Objective-C code. The @synchronized directive does what any other mutex lock would do—it prevents different threads from acquiring the same lock at the same time.


2 Answers

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

like image 100
Tirth Avatar answered Nov 04 '22 18:11

Tirth


@synchronized(self) is used to get rid of the self. prefix.

So in my example I set the strText not in the function I set it in the class.

Two concepts are being conflated.

  1. @synchronized(self) { ... } only locks the block using the self object as the semaphore.
  2. In Objective-C, there is nothing like a hypothetical with statement as in other languages that removes the need for self.whatever to be just whatever. Might want to take the Stanford CS193P online course to brush up on the language.
like image 20
newacct Avatar answered Nov 04 '22 17:11

newacct