On Jun 8, 2014, at 9:30 AM, William Squires <[email protected]> wrote:

>  Okay, I have several classes in my (somewhat large, and growing) project 
> that implement the singleton pattern via a [<classname> shared<whatever>] 
> class method (and a file-scope static reference) that uses lazy loading to 
> instantiate the singleton the first time a reference is asked for.

You've gotten some very good advice from people for setting up a singleton.

I generally use this kind of pattern:

+ (ClassName*)sharedInstance {
        static ClassName* sSingleton = nil;
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
                sSingleton = [ClassName new];
        });
        return sSingleton;
}

This way, unless the object itself requires initialization on a specific thread 
(like CoreData kind of does), then this should be thread-safe and supports lazy 
initialization.  After all, why initialize something that you'll never use?

-- 
Glenn L. Austin, Computer Wizard and Race Car Driver         <><
<http://www.austinsoft.com>


_______________________________________________

Cocoa-dev mailing list ([email protected])

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 [email protected]

Reply via email to