Apple gives a good sample on how to create a singleton class; I've modified it a bit for iOS programming:
Modifications:
static MyGizmoClass *sharedInstance = nil;
+ (MyGizmoClass*) sharedInstance
{
if (sharedInstance == nil) {
sharedInstance = [[super allocWithZone:NULL] init];
}
return sharedInstance;
}
+ (id)allocWithZone:(NSZone *)zone
{
return [[self sharedInstance] retain];
}
- (id)copyWithZone:(NSZone *)zone
{
return self;
}
- (id)retain
{
return self;
}
- (NSUInteger)retainCount
{
return NSUIntegerMax; //denotes an object that cannot be released
}
- (oneway void)release
{
//do nothing
}
- (id)autorelease
{
return self;
}
+ (MyGizmoClass*) sharedInstance
{
if (sharedInstance == nil) {
sharedInstance = [[super allocWithZone:NULL] init];
}
return sharedInstance;
}
+ (id)allocWithZone:(NSZone *)zone
{
return [[self sharedInstance] retain];
}
- (id)copyWithZone:(NSZone *)zone
{
return self;
}
- (id)retain
{
return self;
}
- (NSUInteger)retainCount
{
return NSUIntegerMax; //denotes an object that cannot be released
}
- (oneway void)release
{
//do nothing
}
- (id)autorelease
{
return self;
}
Modifications:
- Used "sharedInstance" method and variable name to make it easier to copy paste.
- - (void) release to - (oneway void) release
The singleton sample produces a warning in the release method because NSObject uses the "oneway" return type modifier. It's basically an indication that the method is used for asynchronous messages. For more details on what oneway does, toodarkpark.net offers a good explanation.
No comments:
Post a Comment