2015-10-14 104 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

此解决方案有利于检入+初始化,因为它将无法编译,而不是在运行时中止。编译错误会告诉用户到底要做什么。 –

相关问题