On Sep 13, 2014, at 9:14 PM, Daryle Walker <dary...@mac.com> wrote:
> 
> I’ve seen bog-standard code to initialize a shared instance like:
> 
>> + (SomeSingleton *) sharedInstance
>> {
>>    static SomeSingleton *sharedInstance = nil;
>>    static dispatch_once_t onceToken;
>>    static dispatch_once_t onceToken;
>>    dispatch_once(&onceToken, ^{
>>        sharedInstance = [[SomeSingleton alloc] init];
>>    });
>>    return sharedInstance;
>> }
> 
> What happens if that initialization fails? Shouldn’t there be a test for NIL 
> and a reset of the “onceToken” somewhere?… (Or is the chance of failure too 
> unlikely?)

Plenty of ObjC code assumes that initialization can’t fail. Sometimes, but not 
always, the fallibility of the initializer is documented. Thankfully Swift puts 
pressure on you to make that assumption explicit.

Besides all that, you can’t reset a dispatch_once. The contract requires that 
you pass it a pointer to a dispatch_once_t that you guarantee has been 
initialized zero for the entire life of the program. Otherwise you’ve just 
moved the race condition from initializing your singleton to initializing the 
dispatch_once.

Technically this means you can’t have a dispatch_once instance variable, as the 
memory at that address may have been nonzero before the object was allocated. 
In practice, I don’t think it’s an issue (nobody should be able to send 
messages to your object until initialization finishes anyway), but I invite 
someone from the runtime team (*cough* Greg Parker *cough*) to explain why I’m 
wrong. :)

--Kyle Sluder
_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Reply via email to