I have found how to implement singleton in objective c (Non-ARC).
// AppTools.h in my code
@interface AppTools : NSObject {
NSString *className;
}
@property ( nonatomic, retain ) NSString *className;
+ ( id ) sharedInstance;
@end // AppTools
// AppTools.m in my code
static AppTools *sharedAppToolsInstance = nil;
@implementation AppTools
@synthesize className;
- ( id ) init {
self = [ super init ];
if ( self ) {
className = [ [ NSString alloc ] initWithString: @"AppTools" ];
}
return self;
} // init
- ( void ) dealloc {
// Should never be called, but just here for clarity really.
[ className release ];
[ super dealloc ];
} // dealloc
+ ( id ) sharedInstance {
@synchronized( self ) {
if ( sharedAppToolsInstance == nil )
sharedAppToolsInstance = [ [ super allocWithZone: NULL ] init ];
}
return sharedAppToolsInstance;
} // sharedInstance
+ ( id ) allocWithZone: ( NSZone * )zone {
return [ [ self sharedInstance ] retain ];
} // allocWithZone:
- ( id ) copyWithZone: ( NSZone * )zone {
return self;
} // copyWithZone:
- ( id ) retain {
return self;
} // retain
- ( unsigned int ) retainCount {
return UINT_MAX; // denotes an object that cannot be released
} // retainCount
- ( oneway void ) release {
// never release
} // release
- ( id ) autorelease {
return self;
} // autorelease
I’d like to know how to work allocWithZone: in sharedInstance method.
On this, the allocWithZone: method’s receiver is ‘super’ and ‘super’ is NSObject.
Though return value is NSObject instance, it is substituted to sharedInstance.
Where is className’s memory room then?
I don’t know how to work this part of the code.
Thank in advance.
You ask “Where is className’s memory room then?”
Most classes do not implement
allocorallocWithZonethemselves but rely on the implementation inherited fromNSObject. TheNSObjectimplementation allocates an object of the original calling class.So in your example
AppToolsdoes overrideallocWithZone, this implementation invokesNSObject‘sallocWithZonevia a call tosuper, andNSObject‘s method performs the actual allocation and returns an object of typeAppTools.[Note: If you are wondering how
NSObject‘s implementation knows what kind of object to allocate then this is simple – calling an inherited method does not alter theselfargument to the method,alloc/allocWithZoneare class methods, and theselfargument of a class method references the class object (rather than an instance object of the class) itself.]