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)"; } }
@synchronized(self) is used to get rid of the self. prefix.
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.
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, includingself.
As Massimo Cafaro pointed out: "It’s safest to create all the mutual exclusion objects before the application becomes multithreaded, to avoid race conditions."
@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.
@synchronized(self) { ... } only locks the block using the self object as the semaphore.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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With