class_replaceMethod类别方法返回nil

时间:2018-06-06 08:16:58

标签: ios

我使用UIViewController类在iOS中进行方法替换。 我编写了一个类别方法- (void)sw_viewWillAppear:(BOOL) animated来替换UIViewController - (void)viewWillAppear:(BOOL) animated

类别代码如下:

- (void)exchangeImp {
    Class aClass = object_getClass(self);
    SEL originalSelector = @selector(viewWillAppear:);
    SEL swizzledSelector = @selector(sw_viewWillAppear:);

    Method originalMethod = class_getInstanceMethod(aClass, originalSelector);
    Method swizzledMethod = class_getInstanceMethod(aClass, swizzledSelector);
    IMP result = class_replaceMethod(aClass, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
    NSLog(@"result is %p", result);}

- (void)sw_viewWillAppear:(BOOL) animated {
     NSLog(@"There do custome things");}

结果始终返回nil,但据我所知,如果方法已存在,class_replaceMethod将返回旧的IMP。旧的IMP应该是sw_viewWillAppear:吗?为什么它返回零?

1 个答案:

答案 0 :(得分:0)

最后,我知道为什么。因为我在exchangeImp中呼叫ViewController而不是UIViewControllerViewControllerUIViewController的子类。我写了UIViewController的类别,因此类别方法将位于UIViewController方法列表中,而不是ViewController!这就是为什么'class_replaceMethod'总是返回nil。