如何在Xcode中打印我的代码的所有方法?

时间:2018-01-12 07:55:30

标签: ios objective-c xcode

如何按顺序打印文件中的所有方法?只需打印一次。

我想打印所有执行的方法。给NSLog(@"%s",__func__),仅打印方法名称。我想得到这样的日志:

2018-01-11 15:31:58.592319+0800 Test[9574:769688] -[ViewController viewDidLoad]
2018-01-11 15:31:58.597790+0800 Test[9574:769688] -[ViewController prepareTableView]
2018-01-11 15:31:58.599040+0800 Test[9574:769688] -[ViewController viewWillAppear:]
2018-01-11 15:31:58.805699+0800 Test[9574:769688] -[ViewController viewWillLayoutSubviews]
2018-01-11 15:31:58.805953+0800 Test[9574:769688] -[ViewController viewDidLayoutSubviews]
2018-01-11 15:31:58.806717+0800 Test[9574:769688] -[ReloadTest reloadData]
2018-01-11 15:31:58.808404+0800 Test[9574:769688] -[ReloadTest layoutSubviews]
2018-01-11 15:31:58.808745+0800 Test[9574:769688] -[ViewController viewWillLayoutSubviews]
2018-01-11 15:31:58.808970+0800 Test[9574:769688] -[ViewController viewDidLayoutSubviews]
2018-01-11 15:31:58.809384+0800 Test[9574:769688] -[ReloadTest layoutSubviews]
2018-01-11 15:31:58.814083+0800 Test[9574:769688] -[ViewController viewDidAppear:]

1 个答案:

答案 0 :(得分:1)

我不确定这是不是你的意思(这将记录按调用顺序调用的方法,而不是类中的所有方法):

@interface Backtracer : NSObject
+ (void)logBacktrace;
@end
@implementation Backtracer
+ (void)logBacktrace {
    NSString *stackSymbols = [NSThread.callStackSymbols.reverseObjectEnumerator.allObjects componentsJoinedByString:@"\n"];
    NSMutableArray *methods = [NSMutableArray array];
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"[\\+\\-]\\[[^\\]]+\\]" options:(NSRegularExpressionOptions)0 error:nil];
    NSArray *matches = [regex matchesInString:stackSymbols options:(NSMatchingOptions)0 range:NSMakeRange(0, stackSymbols.length)];
    for (NSTextCheckingResult *match in matches) {
        NSString *method = [stackSymbols substringWithRange:match.range];
        if ([method hasSuffix:@" logBacktrace]"]) break;
        [methods addObject:method];
    }
    NSLog(@"backtrace:\n\n%@", [methods componentsJoinedByString:@"\n"]);
}
@end

使用这样的类:

@interface MyClass : NSObject
- (void)step0;
- (void)step1:(int)x;
- (void)step2:(int)x;
@end

@implementation MyClass
- (instancetype)init {
    if (self = [super init]) {
        [self step0];
    }
    return self;
}
- (void)step0 {
    [self step1:1];
}
- (void)step1:(int)x {
    [self step2:(x + 1)];
}
- (void)step2:(int)x {
    //Here's how we got here:
    [Backtracer logBacktrace];
}
@end

这样称呼这个人为的例子:

(void)[MyClass new];

结果:

... backtrace:

-[MyClass init]
-[MyClass step0]
-[MyClass step1:]
-[MyClass step2:]