Ich habe eine Lösung für ein Benachrichtigungsproblem, das gut funktioniert, aber ich fürchte, könnte eine schlechte Idee sein.Klassenmethode und Instanzmethode mit dem gleichen Namen in Objective-C
Ich habe eine Benachrichtigung, die von jeder Instanz einer Klasse und von der Klasse selbst behandelt werden muss. Um dies zu behandeln, melde ich mich für eine Benachrichtigung sowohl von der Klasse als auch von den Instanzen der Klasse an. Da es sich um dieselbe Benachrichtigung handelt, habe ich die Methode class und instance gleich benannt. Dies entspricht dem Standard, den wir für die Benennung von Benachrichtigungshandlern festgelegt haben.
Ist das eine schlechte Idee? Gibt es eine versteckte Got'ca, die ich vermisse? Werde ich die zukünftigen Entwickler verwirren?
+ (void)initialize
{
if (self == [SICOHTTPClient class]) {
[[self notificationCenter] addObserver:self
selector:@selector(authorizationDidChangeNotification:)
name:SICOJSONRequestOperationAuthorizationDidChangeNotification
object:nil];
}
}
- (id)initWithBaseURL:(NSURL *)url
{
self = [super initWithBaseURL:url];
if (self) {
self.parameterEncoding = AFJSONParameterEncoding;
[self registerHTTPOperationClass:[SICOJSONRequestOperation class]];
[self setDefaultHeader:@"Accept" value:@"application/json"];
if ([[self class] defaultAuthorization])
[self setDefaultHeader:@"Authorization" value:[[self class] defaultAuthorization]];
[[[self class] notificationCenter] addObserver:self
selector:@selector(authorizationDidChangeNotification:)
name:SICOJSONRequestOperationAuthorizationDidChangeNotification
object:nil];
}
return self;
}
- (void)dealloc
{
[[[self class] notificationCenter] removeObserver:self
name:SICOJSONRequestOperationAuthorizationDidChangeNotification
object:nil];
}
#pragma mark Notifications
- (void)authorizationDidChangeNotification:(NSNotification *)notification
{
NSString *authorization = notification.userInfo[SICOJSONRequestOperationAuthorizationKey];
if ([authorization isKindOfClass:[NSString class]]) {
[self setDefaultHeader:@"Authorization" value:authorization];
} else {
[self clearAuthorizationHeader];
}
}
+ (void)authorizationDidChangeNotification:(NSNotification *)notification
{
NSString *authorization = notification.userInfo[SICOJSONRequestOperationAuthorizationKey];
if ([authorization isKindOfClass:[NSString class]]) {
[self setDefaultAuthorization:authorization];
} else {
[self setDefaultAuthorization:nil];
}
}
Superfrage. Ich habe nicht tausend Punkte, aber ich kann sagen, Instanz- und Klassenmethoden werden nicht in Konflikt geraten, da ihr Bedarf und ihre Implementierung sehr unterschiedlich sind. –