ObjectiveC:Synchronized
lastmod 2026-11-10created 2018-10-122 edits
@synchronized is an Objective-C directive that uses any object as a lock to guarantee that only one thread at a time runs the code inside the block. A reentrant mutex is tied to each object passed in the parentheses, and the lock is released automatically when execution leaves the block or an exception is thrown, which makes it more concise than using NSLock directly. It is commonly used for lazy initialization of singletons and for protecting shared variables, but because of its internal lookup cost, GCD's dispatch_once or os_unfair_lock is recommended where performance matters.
How to use
+(id)getSingletonInstance
{
@synchronized(self)
{
if (singletonObj == nil)
{
singletonObj = [[self alloc] init];
}
return singletonObj;
}
}