use*_*951 4 xcode objective-c nslog
不是调用NSLog或Dlog的函数,而是调用该函数的函数.
我创建了一个类
+(void) computeTime:(void (^)())block
{
NSDate * currentTime = [NSDate date];
block();
DLog ("Time Running is: %f", [[NSDate date] timeIntervalSinceDate:currentTime);
}
Run Code Online (Sandbox Code Playgroud)
因此,每当有一个操作我想测量它的时间时,我会把它放在一个块中.
并执行[Tools computeTime:^ {// operation}];
但是,我想知道调用computeTime的函数.我该怎么办?
两种选择:
第一种是滥用+[NSThread callStackSymbols]来获取调用堆栈中所有符号的数组并拉出你想要的符号.我怀疑这会相对缓慢.
第二是使用宏.C预处理器提供了一个很好的宏__PRETTY_FUNCTION__,它包含所有格式良好的函数名称,并且它也适用于Obj-C方法.而不是[Tools computeTime:^{/*operation*/}]你可以使用类似的东西,[Tools computeTimeWithName:__PRETTY_FUNCTION__ block:^{/*operation*/}]或者你可以将它全部包装在你自己的宏中,这样你就可以说TOOLS_COMPUTE_TIME(^{/*operation*/}):
#define TOOLS_COMPUTE_TIME(...) [Tools computeTimeWithName:__PRETTY_FUNCTION__ block:(__VA_ARGS__)]
Run Code Online (Sandbox Code Playgroud)
注意,我使用了varargs样式的宏,因为C预处理器不能很好地理解obj-c语法,因此块内的任何逗号都将被解释为宏的独立参数.如果我使用它来定义它,TOOLS_COMPUTE_TIME(op)那么编译器会抱怨宏只接受1个参数但它被赋予多个.通过使用varargs,编译器不关心你给它多少个参数,它会将它们全部传递给__VA_ARGS__令牌.
Another possible answer for someone searching for the OP's original question and adding to Kevin's first suggestion to use the call stack.
If you're looking for what called a function (method), consider the following:
NSArray *callStack = [NSThread callStackSymbols];
// Top of the stack. Current method
NSLog(@"Current method: %@", [callStack objectAtIndex:0]);
// Called by
NSLog(@"called by: %@", [callStack objectAtIndex:1]);
Run Code Online (Sandbox Code Playgroud)
It is possible that the stack item looked for is further into stackArray.
Hope this helps find a bug quicker.
| 归档时间: |
|
| 查看次数: |
1794 次 |
| 最近记录: |