There are a whole bunch of ways to make singletons.  Some are much more work 
than others...  Here's how I would modify your code:

// MySingleton.h:

#import <Foundation/Foundation.h>

@interface MySingleton: NSObject {
    NSUInteger someInteger_;
}

@property (nonatomic) NSUInteger someInteger;

+ (MySingleton*) sharedInstance;

@end

// MySingleton.m:

#import <dispatch/dispatch.h>
#import "MySingleton.h"

static MySingleton *stSharedInstance = nil;

@implementation MySingleton

@synthesize someInteger = someInteger_;

+ (MySingleton*) sharedInstance;
{
    dispatch_once(&stSharedInstanceInvoked, ^{
        //use [super alloc] because [self alloc] would try to return the 
singleton
        //use _privateInit so we don't have to override -init
        //by assigning into the static variable here, we don't have to worry 
about the analyzer reporting a leak
        stSharedInstance = [[super alloc] _privateInit];
    });
    return stSharedInstance;
}


+ (id) allocWithZone: (NSZone*) zone {
    //return the shared instance, but retained, since +alloc calls return owned 
objects
    return [stSharedInstance retain];
}

- (id)_privateInit {
    //this is the actual initializer. as long as you don't invoke this 
externally, you're good
    self = [super init];
    if (self) {
        someInteger_ = random() % 1000;
    }
    return self;
}

//if we overrode -init, then you could run into issues if you ever tried to 
alloc/init a MySingleton multiple times

@end

It's a lot shorter, because you don't have to worry about overriding all of the 
<NSObject> memory management methods.  As long as you correctly retain and 
release this object, it will never cease to exist.

Cheers,

Dave
_______________________________________________

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:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

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

Reply via email to