iOS调试技巧

打印哪些方法调用了某个方法

2018-01-17  本文已影响3人  wustzhy
看代码
- (void)printCallersWithCount:(NSInteger)count {
        
        NSArray *syms = [NSThread  callStackSymbols];
        if ([syms count] > 1) {
            
            __block NSArray * arr = syms;
            __block NSInteger num = 0;
            [syms enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                arr;//log
                if ([obj isKindOfClass:[NSString class]] & (num <= count+1)) {
                    
                    if ([obj containsString:[self projName]]) {
                        
                        if (num > 0) {
                            
                            NSString * method = [self getStringWithString:obj start:@"[" end:@"]"];
                            
                            if (method) {
                                NSLog(@" %zd ---- %@",idx,method);
                            }
                        }
                        
                        num++;
                        
                    }
                }
                
            }];
        }
        
    }

    - (NSString *)getStringWithString:(NSString *)string start:(NSString *)start end:(NSString *)end {
        
        if ([string containsString:start] && [string containsString:end]) {
            
            
            NSRange startRange = [string rangeOfString:@"["];
            NSRange endRange = [string rangeOfString:@"]"];
            NSRange range = NSMakeRange(startRange.location + startRange.length-1, endRange.location - startRange.location - startRange.length+2);
            NSString *result = [string substringWithRange:range];
            
            return result;
        }
        
        return nil;
    }
    - (NSString *)projName {
        
        NSString *executableFile = [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString *)kCFBundleExecutableKey];//获取项目名称
        
        return executableFile;
    }
image.png

原理:获取堆栈数组,取出自定义方法打印

上一篇下一篇

猜你喜欢

热点阅读