如何实现方法“ +(BOOL)resolveClassMethod:(SEL)sel”

时间:2018-07-24 03:12:13

标签: objective-c runtime

我正在编写代码时正在学习运行时:

@implementation Son
- (instancetype)init
{
    self = [super init];
    if (self) {
    [self performSelector:@selector(sel) withObject:nil];
    }

    return self;
}

id dynamicMethodIMP(id self, SEL _cmd)
{
    NSLog(@"%s:dynamic method",__FUNCTION__);
    return @"1";
}
+ (BOOL)resolveInstanceMethod:(SEL)sel {
    class_addMethod(self.class, sel, (IMP)(dynamicMethodIMP), "@@:");
    [super resolveInstanceMethod:sel];
    return YES;
}
@end

运行良好。 但是当我编写此代码时:

    @implementation Son
    id dynamicMethodIMP(id self, SEL _cmd)
    {
        NSLog(@"%s:dynamic method",__FUNCTION__);
        return @"1";
    }
    + (BOOL)resolveClassMethod:(SEL)sel {
        class_addMethod(self.class, sel, (IMP)(dynamicMethodIMP), "@@:");
        [super resolveClassMethod:sel];
        return YES;
    }    
    @end
    //Other file
    [Son performSelector:@selector(sel) withObject:nil];

它崩溃了:

  

+ [Son sel]:无法识别的选择器已发送到0x10da8a588类

我应该怎么实现方法+ (BOOL)resolveClassMethod:(SEL)sel

1 个答案:

答案 0 :(得分:1)

self.class替换为object_getClass

+ (BOOL)resolveClassMethod:(SEL)sel {
    class_addMethod(object_getClass(self), sel, (IMP)(dynamicMethodIMP), "@@:");
    [super resolveClassMethod:sel];
    return YES;
}

原因:

  如果参数是类对象,则

object_getClass将返回元类。

如果您阅读中文,则可以阅读我的blog,以了解有关元类的更多详细信息。