iOS开发,hook系统Objective-C的函数
我们都知道在windows下可以通过API轻松的hook很多消息,IOS也可以实现hook的功能。
建立一个
TestHookObject类
// // TestHookObject.m // TestEntrance // // Created by 张 卫平 on 13-6-27. // Copyright (c) 2013年 张 卫平. All rights reserved. // #import "TestHookObject.h" #import <objc/objc.h> #import <objc/runtime.h> @implementation TestHookObject // this method will just excute once + (void)initialize { // 获取到UIWindow中sendEvent对应的method Method sendEvent = class_getInstanceMethod([UIWindow class], @selector(sendEvent:)); Method sendEventMySelf = class_getInstanceMethod([self class], @selector(sendEventHooked:)); // 将目标函数的原实现绑定到sendEventOriginalImplemention方法上 IMP sendEventImp = method_getImplementation(sendEvent); class_addMethod([UIWindow class], @selector(sendEventOriginal:), sendEventImp, method_getTypeEncoding(sendEvent)); // 然后用我们自己的函数的实现,替换目标函数对应的实现 IMP sendEventMySelfImp = method_getImplementation(sendEventMySelf); class_replaceMethod([UIWindow class], @selector(sendEvent:), sendEventMySelfImp, method_getTypeEncoding(sendEvent)); } /* * 截获到window的sendEvent * 我们可以先处理完以后,再继续调用正常处理流程 */ - (void)sendEventHooked:(UIEvent *)event { // do something what ever you want NSLog(@"haha, this is my self sendEventMethod!!!!!!!"); // invoke original implemention [self performSelector:@selector(sendEventOriginal:) withObject:event]; } @end
在Appdelegate里面加入
- (IBAction)btnAction:(id)sender{ NSLog(@"aaa"); } - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease]; // Override point for customization after application launch. self.viewController = [[[ViewController alloc] initWithNibName:@"ViewController" bundle:nil] autorelease]; self.window.rootViewController = self.viewController; [self.window makeKeyAndVisible]; //hook UIWindow‘s SendEvent method TestHookObject *hookSendEvent = [[TestHookObject alloc] init]; [hookSendEvent release]; UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 100, 100)]; btn.center = CGPointMake(160, 240); btn.backgroundColor = [UIColor redColor]; [btn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventAllEvents]; [self.window addSubview:btn]; [btn release]; return YES; }
试着跑起来看看吧。
参考:http://www.cnblogs.com/smileEvday/archive/2013/02/28/Hook.html