首页 > 代码库 > ios runtime 动态向类添加方法

ios runtime 动态向类添加方法

1、定义C函数:

void dynamicMethodIMP(idself, SEL _cmd)

{

    NSLog(@"蜗牛也疯狂");

}


2、重写函数+(BOOL)resolveInstanceMethod:(SEL)sel

+(BOOL)resolveInstanceMethod:(SEL)sel

{

    class_addMethod([selfclass], sel, (IMP)dynamicMethodIMP,"v@:");

    return [superresolveInstanceMethod:sel];

}


3、使用:

 SEL select =NSSelectorFromString(@"resolveThisMethodDynamically");

    [classresolveInstanceMethod:select];

    [[class instance] performSelector:select];