当前位置: 首页> 教育> 锐评 > iOS Hook 崩溃

iOS Hook 崩溃

时间:2025/7/13 4:37:38来源:https://blog.csdn.net/xjh093/article/details/139502032 浏览次数:0次

0x00 崩溃重现

Hook 的类,是这样的:

@interface ViewController : UIViewController
@end@implementation ViewController
- (void)loadView {[super loadView];NSLog(@"%s", __func__);
}- (void)test {NSLog(@"%s", __func__);
}- (void)viewDidLoad {[super viewDidLoad];[self test];
}@end

写的 Hook 逻辑是这样的:

@interface Hook : NSObject
@end#import <objc/runtime.h>
@implementation Hook+ (void)load {NSLog(@"%s", __func__);Class class = NSClassFromString(@"ViewController");Method originalMethod = class_getInstanceMethod(class, NSSelectorFromString(@"loadView"));Method swizzledMethod = class_getInstanceMethod([self class], NSSelectorFromString(@"swizzled_loadView"));method_exchangeImplementations(originalMethod, swizzledMethod);
}- (void)swizzled_loadView {NSLog(@"%s", __func__);[self swizzled_loadView];
}@end

真机运行后,是这样的,直接崩溃:

+[Hook load]
-[Hook swizzled_loadView]
-[ViewController swizzled_loadView]: unrecognized selector sent to instance 0x102e08dd0
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[ViewController swizzled_loadView]: unrecognized selector sent to instance 0x102e08dd0'

0x00 换个方式

写的 Hook 逻辑是这样的:

@interface UIViewController (Hook)
@end#import <objc/runtime.h>
@implementation UIViewController (Hook)+ (void)load {NSLog(@"%s", __func__);Class class = NSClassFromString(@"ViewController");Method originalMethod = class_getInstanceMethod(class, NSSelectorFromString(@"loadView"));Method swizzledMethod = class_getInstanceMethod([self class], NSSelectorFromString(@"swizzled_loadView"));method_exchangeImplementations(originalMethod, swizzledMethod);
}- (void)swizzled_loadView {NSLog(@"%s", __func__);[self swizzled_loadView];UIView *view = [[UIView alloc] init];view. frame = CGRectMake (100, 200, 200, 200);view.backgroundColor = [UIColor redColor];[self.view addSubview:view];
}@end

真机运行后,不崩溃了:

+[UIViewController(Hook) load]
-[UIViewController(Hook) swizzled_loadView]
-[ViewController loadView]
-[ViewController test]

并且成功,添加了 view


关键字:iOS Hook 崩溃

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: