避免程序出现 unrecognized selector 闪退问题

本文介绍了一种在Objective-C中通过方法交换实现运行时行为修改的技术。具体展示了如何利用`class_getInstanceMethod`获取方法并使用`method_exchangeImplementations`进行方法替换,以此改变NSObject的行为。文中提供的代码示例包括了`methodSignatureForSelector:`和`forwardInvocation:`方法的交换实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

给NSObject添加分类

加入代码

+(void)load{

    Method method1 = class_getInstanceMethod(self.class, @selector(methodSignatureForSelector:));

    Method method2 = class_getInstanceMethod(self.class, @selector(mymethodSignatureForSelector:));

    method_exchangeImplementations(method1, method2);


    

    Method method3 = class_getInstanceMethod(self.class, @selector(forwardInvocation:));

    Method method4 = class_getInstanceMethod(self.class, @selector(myforwardInvocation:));

    method_exchangeImplementations(method3, method4);

}


-(NSMethodSignature*)mymethodSignatureForSelector:(SEL)selector

{

    NSMethodSignature *signature = [NSMethodSignature signatureWithObjCTypes:@encode(void)];

    return signature;

}


- (void)myforwardInvocation:(NSInvocation *)invocation {


}


做法比较霸道

参考:https://www.jianshu.com/p/c89b2716d60d

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值