我有一個適用於通知問題的解決方案,但我擔心這可能不是個好主意。在Objective-C中具有相同名稱的類方法和實例方法
我有一個通知,需要由類的每個實例和類本身來處理。爲了處理這個問題,我正在註冊類和類的通知。因爲它是完全相同的通知,所以我已經將類和實例方法命名爲相同。這遵循我們爲通知處理程序的命名方式設定的標準。
這是一個壞主意?是否有一些隱藏的got'ca,我錯過了。我會混淆未來的開發者嗎?
+ (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];
}
}
超級問題。我沒有千點,但我可以說,實例和類方法不會衝突,因爲它們的需求和實現是非常不同的。 –