Check if subclass overrides a method

前端 未结 7 2274
耶瑟儿~
耶瑟儿~ 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:13

    Adapted for Swift 4.0 (and added an optional baseClass BELOW which the algorithm looks for overrides):

    extension NSObject {
    
        func checkIf(overrides selector: Selector, baseClass: AnyClass? = nil) -> Bool {
            guard var objSuperClass = self.superclass else { return false }
    
            var isOverridden = false
    
            while objSuperClass != nil {
                isOverridden = object.method(for: selector) != objSuperClass?.instanceMethod(for: selector)
                if isOverridden {
                    break
                }
                objSuperClass = objSuperClass?.superclass()
                if objSuperClass == baseClass {
                    break
                }
            }
    
            return isOverridden
        }
    }
    

提交回复
热议问题