Re: How to implement readonly property
Re: How to implement readonly property
- Subject: Re: How to implement readonly property
- From: Greg Parker <email@hidden>
- Date: Sat, 08 Dec 2012 18:51:44 -0800
On Dec 8, 2012, at 5:27 PM, Richard Heard <email@hidden> wrote:
> Greg,
>
> So, from what you are saying, either of these snippets should be valid, right?
>
>> +(id)sharedInstance{
>> static id _sharedInstance = nil;
>>
>> if (!_sharedInstance){
>> @synchronized([self class]){
>> if (!_sharedInstance){
>> id sharedInstance = [[super allocWithZone:NULL] init];
>> OSMemoryBarrier();
>> _sharedInstance = sharedInstance;
>> }
>> }
>> }
>>
>> OSMemoryBarrier();
>> return _sharedInstance;
>> }
>
> vs
>
>> +(id)sharedInstance{
>> static id _sharedInstance = nil;
>>
>> static dispatch_once_t onceToken;
>> dispatch_once(&onceToken, ^{
>> _sharedInstance = [[super allocWithZone:NULL] init];
>> });
>>
>> return _sharedInstance;
>> }
>
>
> Any massive advantages / disadvantages with either approach?
Use dispatch_once(). It is shorter, simpler, and more obviously correct. The memory barrier implementation may also be correct, but why take the risk?
--
Greg Parker email@hidden Runtime Wrangler
_______________________________________________
Cocoa-dev mailing list (email@hidden)
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:
This email sent to email@hidden