Cocoa: Break on every method call?

Often when debugging, it's important for me to know what methods of a class are being called in what order. The naive solution (that I've been using thus far) is to pop an NSLog at the top of each method. But this is time consuming, repetitive, ugly, and makes my code look juvenile if I forget to remove the logs after debugging.

A cleaner solution is to set breakpoints on each of my methods, configure their actions to issue the debugger command: po NSStringFromSelector(_cmd) and set them to automatically continue. This is prettier and saves me from having to remember to remove all those NSLog s, but is no less repetitive or time consuming.

What I really want is a way to set a symbolic breakpoint that breaks on every method (of a class? Of a module?). Any debugging/runtime masters have a solution or tips on where to start looking?


All Objective-C method calls go through one of the C runtime calls objc_msgSend , objc_msgSend_stret , objc_msgSendSuper and objc_msgSendSuper_stret per the 'Sending Messages' section of the Objective-C Runtime Reference. So you should be able to trap those, and give them actions to log the relevant parts of the first two parameters (it's target and selector for the normal sends, a struct describing the superclass that contains both the target and the class type for super calls).


Use a logging system like Log4Cocoa. Logging the method, line number, and file from which it was called is a basic function of such logging systems.

Each logging call is given a detail level, specifying under what conditions it should log. You would then set the detail level to get the desired amount of information. Products built for release, for examples, would only log errors and perhaps warnings; debug level would log everything.


I think your current approach of putting a breakpoint on each method of interest is the best bet. As @Tommy explained, there's a small number of message dispatch functions in the runtime that you can break on, but I having the debugger evaluate a conditional breakpoint on every single message send will probably slow your application down significantly.

One way to make setting your breakpoints a little easier is to do it from a GDB command file. Put the commands to set the breakpoints for all the methods of interest in a single file that you can load at the beginning of your debug session. Setting all the breakpoints in a single file gives you one place to edit the list, and editing the file should be easy with copy and paste.

Perhaps the best solution, but the one that'll take a little time to master, is to use Instruments. You'll want to read up on the DTrace mechanism first, but you can easily create a custom instrument with probes on each of the methods of interest. Instruments is incredibly powerful, but it takes some time to learn to really use it.

链接地址: http://www.djcxy.com/p/47382.html

上一篇: @import vs #import

下一篇: 可可:打破每一个方法调用?