2015-10-14 101 views
2

我已經在我的課我可以檢測到:「基類的類重載方法」嗎?

- (void)configureWithDictionary:(NSDictionary*)dictionary; 
- (void)configureWithDictionary:(NSDictionary*)dictionary withOptions:(XWTreeItemConvertationToNSDictionaryOption*)options; 

兩個方法我都實現了他們兩個。所以!解決方案,如:「只需添加NSAssert(NO,@」你肥大重寫此方法「),」不會幫助=(

- (void)configureWithDictionary:(NSDictionary*)dictionary withOptions:(XWTreeItemConvertationToNSDictionaryOption*)options; 
{ 
    NSAssert(NO, @"You mast override this method" 
} 

因爲我那邊有一些代碼,需要重載的方法寫[super configureWithDictionary:dictionary withOptions:options]; 。每個人都可以使用這個方法。而我兩者都需要!不過。

如果一些開發商將超載-[MYClass configureWithDictionary:]它可以「工作不正確」的。就因爲此方法不調用任何時間,所以我需要寫在控制檯的東西。例如:「Please overload method:-[MYClass configureWithDictionary:withOptions:]」。我想在此方法中只處理一次:

+ (void)initialize 
{ 
    if (self == [self class]) { 

    } 
} 

但我找不到任何解決方案(在文檔/谷歌/ stackoverflow)。並且不能處理:「開發人員基類的重載方法」。

可能會有一些更好的解決方案。但我認爲它應該是最好的。如果你有一些其他的想法。請寫下波紋管=)

我找到了唯一的方法:+[NSObject instancesRespondToSelector],當然我知道關於-[NSObject respondsToSelector:],但如你所知它總是返回YES。我需要幾乎相同,但對於當前階級忽視基地。

PS。任何方式感謝您的關注。鏈接到文檔或一些文章將非常有幫助。

回答

0

我已經找到解決辦法我自己,我認爲這可以幫助社區。所以3個簡單的步驟。

第1步:與方法

+ (NSArray*)methodNamesForClass_WithoutBaseMethodsClasses 
{ 
    unsigned int methodCount = 0; 
    Method *methods = class_copyMethodList(self, &methodCount); 
    NSMutableArray *array = [NSMutableArray arrayWithCapacity:methodCount]; 
    for (unsigned int i = 0; i < methodCount; i++) { 
     Method method = methods[i]; 
     [array addObject:[NSString stringWithFormat:@"%s", sel_getName(method_getName(method))]]; 
    } 
    free(methods); 
    return [array copy]; 
} 

步驟2創建類的形式NSObject的:檢查你做重載類某種方法:

[[self methodNamesForClass_WithoutBaseMethodsClasses] containsObject:NSStringFromSelector(@selector(configureWithDictionary:))] 

第3步:檢查所有你+ (void)initialize需要什麼。它爲類調用一次(所以它不會佔用很多CPU時間)。它只需要開發人員。 So Add #ifdef DEBUG指令

+ (void)initialize 
{ 
    if (self == [self class]) { 
#ifdef DEBUG 
     if ([[self methodNamesForClass_WithoutBaseMethodsClasses] containsObject:NSStringFromSelector(@selector(configureWithDictionary:))] && ![[self methodNamesForClass_WithoutBaseMethodsClasses] containsObject:NSStringFromSelector(@selector(configureWithDictionary:withOptions:))]) { 
      NSAssert(NO, @"Please override method: -[%@ %@]", NSStringFromClass([self class]), NSStringFromSelector(@selector(configureWithDictionary:withOptions:))); 
     } 
#endif 
    } 
} 

勝利!

2

可能是它不正是你所求的是什麼,但是當我需要確保子類重載了一些必要的方法,我做這樣的事情:

@protocol SomeClassRequiredOverload 

- (void) someMethodThatShouldBeOverloaded; 

@end 

@interface _SomeClass 
@end 

typedef _SomeClass<SomeClassRequiredOverload> SomeClass; 
+0

這是一個很好的把戲。我會在我的工作中使用它。謝謝=)!但是這對於爲外國開發者找到問題無能爲力。 Sad =( – ZevsVU

+0

此解決方案有利於檢入+初始化,因爲它將無法編譯,而不是在運行時中止。編譯錯誤會告訴用戶到底要做什麼。 –

相關問題