intercept all objective c method calls

2019-08-18 14:41发布

I wish to insert hooks whenever a method is called in my iOS app. So lets say there is a selector X, I wish to log "Method X starting" before the method executes, and then log "Method X ended" after the execution. I am aware of an approach where I can swizzle the implementation of sel X with the one which has the hook before and after the call to "itself", so that I can be notified when the method has executed. But, this will only work if i know the method in advance. I wish to insert hooks for all the methods that execute, even if I do not have access to the source code of the class executing it (for example a third party closed library executing an internal method). The intent behind this is logging the time taken for execution of each and every method in my app. I am aware that I cannot override objc message send method call to intercept methods. Does NSObject have some functions that are called before and after a method gets executed?

2条回答
走好不送
2楼-- · 2019-08-18 15:12

It sounds like what you actually want is to run your app in Instruments' "Time Profiler" tool. This will log all the method invocations for you and show you which ones are taking the greatest amount of time in your app.

To answer your original question, you don't actually have to know the methods ahead of time; you can just use class_copyMethodList() to get a list of methods and then iterate over them. I would discourage actually going this route, though, as Instruments is a better tool for this sort of thing.

查看更多
走好不送
3楼-- · 2019-08-18 15:28

Believe me you don't want this. As you think on a higher level that calling a function and logging the start and end to it is good, it won't do you any good for the following reasons:

1- Function will call many many lower level fuctions: addSubview itself will call many functions alone, and the function it calls will call many fuctions inside as well. You think you are about to call 1 function, but this log will be triggered +20 times in this case.

2- logging all functions is actually extra code in your case. Extra code means extra effort to the app. What you will do is basically impact the performance and battery usage dramatically.

3- Apple makes sure its core functions are seriously optimized and spends a lot of time on them to ensure they are at their best (in some xCode releases they are updated as well)

My advice is to log your functions, if you're trying to achieve a specific goal. but generally logging objective c is not recommended.

PS: In case you are trying to check the time for every function, there are tools that will show you which functions are taking what times.

查看更多
登录 后发表回答