我感到困惑不解的是,在创建单一州法院时,这一法典(载于《科恰丰通斯指南》)压倒了某些方法。
static id sharedReactor = nil;
+(id)sharedInstance {
if(sharedReactor == nil) sharedReactor = [[super allocWithZone:NULL] init];
return sharedReactor;
}
。
+(id)allocWithZone:(NSZone *)zone {
return[[self sharedInstance] retain];
}
-(id)retain {
return self;
}
In the code where the singleton instance is created the +sharedInstance method calls [super allocWithZone:NILL] from the superclass (which in my case is NSObject) The allocWithZone above is only called if you attempt to use it to create a new singleton。
The bit I am confused about is the use of retain, especially seeing as retain is also overridden to return self。 Can anyone explain this, could it not be written:
+(id)allocWithZone:(NSZone *)zone {
return [self sharedInstance];
}
-(id)retain {
return self;
}
<>strong>EDIT_001:
Based on comments and reading various posts on the web I have decided to go with the following (see below) I have chosen to go for a shared singleton approach where if needed I would have the option of creating a second or third instance。 Also at this stage as I am only using the singleton for the model portion of MVC for a simple iPhone app I have decided to leave thread safety out。 I am aware its important and as I get more familiar with iPhone programming I will likely use +initialize instead (keeping in mind the subclass issue where it can be called twice) Also I have added a dealloc, firstly to log a message should the singleton be released, but also to clean things up properly should the singleton be no longer required。
@interface SharedManager : NSObject
+(id)sharedInstance;
@end
@implementation SharedManager
static id myInstance = nil;
+(id)sharedInstance {
if(myInstance == nil) {
myInstance = [[self alloc] init];
}
return myInstance;
}
-(void)dealloc {
NSLog(@"_deal: %@", [self class]);
[super dealloc];
myInstance = nil;
}
@end
In testing I found that I had a set the static variable to nil in the dealloc or it maintained its pointer to the original object。 I was initially a little confused by this as I was expecting the scope of the static to be the instance, I guess its the class instead, which makes sense。
厨师