Reputation: 16256
I'm implementing the textbook-singleton in Objective-C:
+ (instancetype) sharedSingleton
{
id sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[self alloc] init];
});
return sharedInstance;
}
...as I have been doing for a while. When changing an old @synchronized
-syntax singleton to this kind, in an old project (open in the latest version of Xcode), I get the error:
Variable is not assignable (missing __block type specifier)
...pointing at the allocation line. I have the exact same code in many parts of other code, built and run with the same environment, and never an issue... What's going on? Should I prepend the __block
qualifier and be done with it, or is there more than meets the eye here?
The only thing I can think of is, this old project I'm modernising right now has NOT been transitioned to ARC... (yet)
Upvotes: 0
Views: 147
Reputation: 56635
You are missing static
on the sharedInstance
variable. That line should be
static id sharedInstance = nil;
Colin Wheelas has a good and short article about how to create singeltons using dispatch_once.
Upvotes: 4