Check if subclass overrides a method

前端 未结 7 2270
耶瑟儿~
耶瑟儿~ 2021-02-09 13:15

Is it possible to check whether a subclass implements a method that exists either in its immediate superclass or in some superclass of its superclass, etc?

E.g. I subcla

7条回答
  •  温柔的废话
    2021-02-09 14:11

    Based on this answer by Mert Buran.

    You can create a simple method to check whether a given object overrides a given selector (method):

    -(BOOL)checkIfObject:(id)object overridesSelector:(SEL)selector {
    
        Class objSuperClass = [object superclass];
        BOOL isMethodOverridden = NO;
    
        while (objSuperClass != Nil) {
    
            isMethodOverridden = [object methodForSelector: selector] !=
            [objSuperClass instanceMethodForSelector: selector];
    
            if (isMethodOverridden) {
                break;
            }
    
            objSuperClass = [objSuperClass superclass];
        }
    
        return isMethodOverridden;
    }
    

    This can be called as follows:

    [self checkIfObject:someObject overridesSelector:@selector(someSelector)];
    

提交回复
热议问题