At 7:56 PM +0700 11/12/12, Gerriet M. Denkmann wrote:
- (NSDictionary *)someDictionary;
{
        static NSDictionary *someDictionary;
        static dispatch_once_t justOnce;
        dispatch_once( &justOnce, ^
                {
                        // create a temp dictionary (might take some time)
                        someDictionary = temp;
                }
        );

        return someDictionary;
}

Here's what I usually do:

assume that _someDictionary is an instance variable initialized to nil and never changed once initialized to non-nil

- (NSDictionary *)someDictionary;
{
  if (!_someDictionary)
  {
    @synchronized (self)
    {
      if (!_someDictionary)
      {
        // create a temp dictionary (might take some time)
         _someDictionary = temp;
      }
    }
  }

  return _someDictionary;
}

the outer if avoids the overhead of @synchronized if _someDictionary is already created -- this is just an optimization

the inner if is necessary to resolve the race condition if multiple threads make it past the outer one

HTH,

-Steve
_______________________________________________

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