Re: Proper way to create a singleton without @synchronized ?
Re: Proper way to create a singleton without @synchronized ?
- Subject: Re: Proper way to create a singleton without @synchronized ?
- From: Dave DeLong <email@hidden>
- Date: Sat, 16 Apr 2011 20:18:30 -0700
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 (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