简体   繁体   中英

Prepend NSLog to all methods in Objective-C

Is it possible to configure a class, such that each method calls :

"NSLog(@"%s", __PRETTY_FUNCTION__);" 

prior to executing?

For example, given:

@implementation myClass

- (void) methodA {
    NSLog(@"Do something in method A");
}

- (void) methodB {
    NSLog(@"Do something in method B");
}

@end

the output from [myClass methodA] would be :

"-[myClass methodA]"

"Do something in method A"

instead of:

"Do something in method A"

Thank you.

There are clever ways one could do this, but assuming this is just for debugging a class you've written and there are too many methods to do it by hand why not just use Find & Replace?

Note: your opening brace is at the end of the line in the code you show the following uses that, if you change your style you'll need to change the regular expression.

In Xcode make sure pattern matching is on: click the magnifying glass to the left of the search entry box, select Edit Find Options... , then set Matching Style to Regular Expression

Now in the search field enter:

^-[^{]+\{

That matches: beginning of line ( ^ ), dash ( - ), not a brace ( [^{] ) one or more times ( + ), and finally a brace ( \\{ ).

Do a few searches to make sure it is matching what you think. Then in the Replace field type:

\0 NSLog(@"%s", __PRETTY_FUNCTION__);

which replaces what was matched ( \\0 ) followed by your NSLog call.

Reversing the process can be done similarly, that is left as an exercise.

HTH

I've created a library specifically for this sort of things. Check out Xcode Logger on GitHub.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM