- no instanciation
- one class method do the all necessary job
- first time of the class method call > create single instance
- other class method calls > return already created instance
- how to use?
- include singleton class's header file
- use class method to obtain class instance
Sample Class's header file
@interface SampleClass : NSObject + (SampleClass*)sharedInstance; @end
Sample Class's source file
@implementation SampleClass
static SampleClass *sharedInstance = nil; // shared instance
+ (SampleClass*)sharedInstance
{
@synchronized(self)
{
if (sharedInstance == nil)
sharedInstance = [[super allocWithZone:nil] 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; // object cannot be released
}
- (oneway void)release
{
// do nothing
}
- (id)autorelease
{
return self;
}
No comments:
Post a Comment