L'applicazione delegato è un posto ragionevole per metterlo. Un'altra opzione potrebbe essere quella di creare una classe factory singleton personalizzata che abbia un metodo di classe che restituisce il delegato del gestore località e implementa i metodi delegati. Ciò manterrebbe la tua classe di delegati delle app più pulita.
Ecco uno scheletro di implementazione di classe singleton basato su "Singletons in Cocoa: Doing them wrong" di Peter Hosey. Questo potrebbe essere eccessivo, ma è un inizio. Aggiungi i tuoi metodi delegati alla fine.
static MyCLLocationManagerDelegate *sharedInstance = nil;
+ (void)initialize {
if (sharedInstance == nil)
sharedInstance = [[self alloc] init];
}
+ (id)sharedMyCLLocationManagerDelegate {
//Already set by +initialize.
return sharedInstance;
}
+ (id)allocWithZone:(NSZone*)zone {
//Usually already set by +initialize.
@synchronized(self) {
if (sharedInstance) {
//The caller expects to receive a new object, so implicitly retain it
//to balance out the eventual release message.
return [sharedInstance retain];
} else {
//When not already set, +initialize is our caller.
//It's creating the shared instance, let this go through.
return [super allocWithZone:zone];
}
}
}
- (id)init {
//If sharedInstance is nil, +initialize is our caller, so initialze the instance.
//If it is not nil, simply return the instance without re-initializing it.
if (sharedInstance == nil) {
if ((self = [super init])) {
//Initialize the instance here.
}
}
return self;
}
- (id)copyWithZone:(NSZone*)zone {
return self;
}
- (id)retain {
return self;
}
- (unsigned)retainCount {
return UINT_MAX; // denotes an object that cannot be released
}
- (void)release {
// do nothing
}
- (id)autorelease {
return self;
}
#pragma mark -
#pragma mark CLLLocationManagerDelegateMethods go here...
fonte
2009-12-07 19:32:50
Come potrei fare per l'implementazione di una classe singleton fabbrica? Sembra un modo pulito per andare, ma non sono sicuro al 100% da dove cominciare. – joec
Vedere l'esempio sopra. –
la formattazione del codice non ha funzionato (mi dispiace!) – joec