intercept all objective c method calls

旧时模样 提交于 2019-12-24 19:01:48

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/45694335/intercept-all-objective-c-method-calls

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!