iOS 利用runtime实现的Method Swizzling

本文介绍了Objective-C中如何使用runtime API动态获取类的方法并进行替换,通过实例展示了class_getInstanceMethod和method_exchangeImplementations的使用方法,提供了一个在运行时修改类行为的实用技巧。

OC提供了很多API来动态的获取class的类方法、实例方法、类名、实例名等,其原理就是利用runtime实现的

打开Runtime.h 我们可以看到



isa指针和objc_method_list的指针列表

isa的关系图如下:(该图来自这里


实例isa指向类,类的isa指向元类,而类之间又是继承关系,元类之间也是继承关系,

所以只要传相应的类名就可以获取其类里面的所有实例或者方法而不需要知道它的代码。

Method Swizzling就是获取类里面的具体方法,然后可以进行覆盖,添加,修改等

上代码:

#import <Foundation/Foundation.h>
#import <objc/runtime.h>

@interface father : NSObject

@end
@implementation father
-(void)printSome{
    NSLog(@"father");
}

@end

@interface child : father

@end
@implementation child

-(void)printSome{
    NSLog(@"child");
}

@end

@interface other : NSObject
+ (instancetype)personWithName;
@end

@implementation other

-(void)printSome{
    NSLog(@"other");
}

+(instancetype)personWithName{
    
    other *ot=[[other alloc]init];

    return ot;
}

@end

int main(int argc, const char * argv[]) {
    
    father *fa=[[father alloc]init];
    [fa printSome];
    father *ch=[[child alloc]init];
    [ch printSome];
    other *ot=[other personWithName];
    [ot printSome];
    Method oldMethod1=class_getInstanceMethod([father class], @selector(printSome));
    Method newMethod1=class_getInstanceMethod([other class], @selector(printSome));
    method_exchangeImplementations(oldMethod1, newMethod1);
    
    [fa printSome];
    [ot printSome];
    @autoreleasepool {
        // insert code here...
        NSLog(@"Hello, World!");
    }
    return 0;
}

上面的方法:

class_getInstanceMethod 获取class的实例方法。

method_exchangeImplementations 交换两个方法


更多的方法请参考: 官方文档


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值