iOS 获取调用栈信息

参考文献:https://www.jianshu.com/p/a027fdfd6e4f

有两种方法:

1. void* callstack[128];
    int frames = backtrace(callstack, 128);
    char **strs = backtrace_symbols(callstack, frames);

2.NSArray *csss = [NSThread callStackSymbols];

 

import "WTRunloopVC.h"
#import "WTRunloopTest.h"
#include <libkern/OSAtomic.h>
#include <execinfo.h>

@interface WTRunloopVC () 

@end

@implementation WTRunloopVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self performSelector:@selector(testVC) onThread:[WTRunloopTest shareThread] withObject:nil waitUntilDone:NO];
    
}

-(void)testVC {
    NSLog(@"%@ - %@", NSStringFromClass([self class]), NSStringFromSelector(_cmd));
    
    //方法1:方法调用的堆栈信息
    void* callstack[128];
    int frames = backtrace(callstack, 128);
    char **strs = backtrace_symbols(callstack, frames);
    int i;
    NSMutableArray *backtrace = [NSMutableArray arrayWithCapacity:frames];
    for (i = 0;i < 4;i++){
        [backtrace addObject:[NSString stringWithUTF8String:strs[i]]];
    }
    free(strs);
    NSLog(@"=====>>>>>堆栈<<<<<=====\n%@",backtrace);

    //方法2:方法调用的堆栈信息
    NSArray *csss = [NSThread callStackSymbols];
    NSLog(@"=====>>>>>堆栈<<<<<=====\n%@",csss);
}

打印结果:

//方法1.打印的堆栈信息
(
    "0   TotalDemo                           0x00000001063254bc -[WTRunloopVC testVC] + 188",
    "1   Foundation                          0x000000010748f7bc __NSThreadPerformPerform + 331",
    "2   CoreFoundation                      0x0000000108828db1 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17",
    "3   CoreFoundation                      0x0000000108828633 __CFRunLoopDoSources0 + 243"
)
//方法2.打印的堆栈信息
Printing description of csss:
<_NSCallStackArray 0x600003b492c0>(
0   TotalDemo                           0x00000001063255f2 -[WTRunloopVC testVC] + 498,
1   Foundation                          0x000000010748f7bc __NSThreadPerformPerform + 331,
2   CoreFoundation                      0x0000000108828db1 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17,
3   CoreFoundation                      0x0000000108828633 __CFRunLoopDoSources0 + 243,
4   CoreFoundation                      0x0000000108822cef __CFRunLoopRun + 1231,
5   CoreFoundation                      0x00000001088224d2 CFRunLoopRunSpecific + 626,
6   Foundation                          0x0000000107479f88 -[NSRunLoop(NSRunLoop) runMode:beforeDate:] + 277,
7   TotalDemo                           0x000000010635ea27 +[WTRunloopTest testShareThread] + 375,
8   Foundation                          0x000000010748f24b __NSThread__start__ + 1197,
9   libsystem_pthread.dylib             0x000000010a9522eb _pthread_body + 126,
10  libsystem_pthread.dylib             0x000000010a955249 _pthread_start + 66,
11  libsystem_pthread.dylib             0x000000010a95140d thread_start + 13
)

 

 


版权声明:本文为wzt1229原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。