美文网首页iOS 的那些事儿
iOS 获取当前方法的调用者

iOS 获取当前方法的调用者

作者: 你猜我猜不猜你猜我猜不猜 | 来源:发表于2018-01-31 10:09 被阅读777次

    获取堆栈信息后解析

      // 此方法转自别处
      NSArray *syms = [NSThread  callStackSymbols]; 
      NSLog(@"<%@ %p> %@ - caller: %@ ", [self class], self, NSStringFromSelector(_cmd),[syms objectAtIndex:1]);
      NSString *string = [[[syms objectAtIndex:1] componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"[]"]] objectAtIndex:1];
    

    举个例子
    创建类A类B


    image.png

    类A:

    @interface A : NSObject
    
    - (void)callB;
    
    @end
    
    
    @implementation A
    
    - (void)callB{
        B *b = [B new];
        [b method];
    }
    @end
    
    

    类B:

    @interface B : NSObject
    
    - (void)method;
    
    @end
    
    @implementation B
    - (void)method{
        NSArray *syms = [NSThread  callStackSymbols];
        NSLog(@"<%@ %p> %@ - caller: %@ ", [self class], self, NSStringFromSelector(_cmd),[syms objectAtIndex:1]);
    }
    @end
    

    输出LOG

    2018-01-31 09:58:25.568186+0800 Test[23788:4600557] 
    <B 0x600000018490> method - caller: 1   Test 0x000000010bc999a5 -[A callB] + 69
    
    [A callB]
    

    B类method方法在A类callB方法调用

    直接获取到字符串A callB

     NSString *string = [[[syms objectAtIndex:1] componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"[]"]] objectAtIndex:1];
    

    相关文章

      网友评论

        本文标题:iOS 获取当前方法的调用者

        本文链接:https://www.haomeiwen.com/subject/rkhkzxtx.html