Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to NSLog calling function

Not the function calling the NSLog or Dlog but function that call that function.

I created a class

+(void) computeTime:(void (^)())block
{
    NSDate * currentTime = [NSDate date];
    block();
    DLog ("Time Running is: %f", [[NSDate date] timeIntervalSinceDate:currentTime);
}

So everytime there is an operation whose time I want to measure I will put that in a block instead.

and do [Tools computeTime:^{//operation}];

However, I want to know the function that call that computeTime. How do I do so?

like image 365
user4951 Avatar asked Dec 10 '22 06:12

user4951


1 Answers

Two options:

The first is to abuse +[NSThread callStackSymbols] to get an array of all the symbols in the call stack and pull out the one you want. I suspect this is going to be relatively slow.

The second is to use a macro. The C preprocessor provides a nice macro called __PRETTY_FUNCTION__ which contains the name of the function all nicely formatted, and it works well for Obj-C methods as well. Instead of [Tools computeTime:^{/*operation*/}] you can either use something like [Tools computeTimeWithName:__PRETTY_FUNCTION__ block:^{/*operation*/}] or you could wrap it all up in your own macro so you can say TOOLS_COMPUTE_TIME(^{/*operation*/}):

#define TOOLS_COMPUTE_TIME(...) [Tools computeTimeWithName:__PRETTY_FUNCTION__ block:(__VA_ARGS__)]

Note, I've used a varargs-style macro because the C Preprocessor doesn't understand obj-c syntax very well, so any commas inside your block will be interpreted as separate arguments to the macro. If I defined it using TOOLS_COMPUTE_TIME(op) then the compiler would complain that the macro only takes 1 argument but it was given multiple. By using varargs the compiler doesn't care how many arguments you give it, and it will pass them all on to the __VA_ARGS__ token.

like image 103
Lily Ballard Avatar answered Dec 27 '22 01:12

Lily Ballard