ios - Objective C找到方法的调用者

有没有办法确定从某个method调用的代码行?

ennuikiller asked 2019-09-10T09:00:22Z
11个解决方案
179 votes

StackI希望这有助于:

    NSString *sourceString = [[NSThread callStackSymbols] objectAtIndex:1];
    // Example: 1   UIKit                               0x00540c89 -[UIApplication _callInitializationDelegatesForURL:payload:suspended:] + 1163
    NSCharacterSet *separatorSet = [NSCharacterSet characterSetWithCharactersInString:@" -[]+?.,"];
    NSMutableArray *array = [NSMutableArray arrayWithArray:[sourceString  componentsSeparatedByCharactersInSet:separatorSet]];
    [array removeObject:@""];

    NSLog(@"Stack = %@", [array objectAtIndex:0]);
    NSLog(@"Framework = %@", [array objectAtIndex:1]);
    NSLog(@"Memory address = %@", [array objectAtIndex:2]);
    NSLog(@"Class caller = %@", [array objectAtIndex:3]);
    NSLog(@"Function caller = %@", [array objectAtIndex:4]);
intropedro answered 2019-09-10T09:00:35Z
49 votes

在完全优化的代码中,没有100%可靠的方法来确定某个方法的调用者。 编译器可以使用尾调用优化,而编译器有效地重新使用调用者的堆栈帧用于被调用者。

要查看此示例,请使用gdb在任何给定方法上设置断点,然后查看回溯。 请注意,在每次方法调用之前都没有看到objc_msgSend()。 这是因为objc_msgSend()对每个方法的实现进行尾调用。

虽然您可以编译未优化的应用程序,但您需要所有系统库的非优化版本才能避免这一问题。

这只是一个问题; 实际上,你问“我如何重新发明CrashTracer或gdb?”。 一个非常难以解决的职业问题。 除非你想要“调试工具”成为你的职业,否则我建议不要走这条路。

你真的想回答什么问题?

bbum answered 2019-09-10T09:01:26Z
9 votes

使用intropedro提供的答案,我想出了这个:

#define CALL_ORIGIN NSLog(@"Origin: [%@]", [[[[NSThread callStackSymbols] objectAtIndex:1] componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"[]"]] objectAtIndex:1])

这将简单地返回原始类和功能:

2014-02-04 16:49:25.384 testApp[29042:70b] Origin: [LCallView addDataToMapView]

附: - 如果使用performSelector调用函数,结果将是:

Origin: [NSObject performSelector:withObject:]
Guntis Treulands answered 2019-09-10T09:02:05Z
6 votes

Swift 2.0版@Intropedro的答案供参考;

let sourceString: String = NSThread.callStackSymbols()[1]

let separatorSet :NSCharacterSet = NSCharacterSet(charactersInString: " -[]+?.,")
let array = NSMutableArray(array: sourceString.componentsSeparatedByCharactersInSet(separatorSet))
array.removeObject("")

print("Stack: \(array[0])")
print("Framework:\(array[1])")
print("Memory Address:\(array[2])")
print("Class Caller:\(array[3])")
print("Method Caller:\(array[4])")
Geoff H answered 2019-09-10T09:02:42Z
5 votes

如果是为了调试,请养成NSLog(@"%s", __FUNCTION__);的习惯

作为类中每个方法的第一行。 然后,您始终可以通过查看调试器来了解方法调用的顺序。

Giovanni answered 2019-09-10T09:03:13Z
5 votes

刚写了一个方法来为你做这个:

- (NSString *)getCallerStackSymbol {

    NSString *callerStackSymbol = @"Could not track caller stack symbol";

    NSArray *stackSymbols = [NSThread callStackSymbols];
    if(stackSymbols.count >= 2) {
        callerStackSymbol = [stackSymbols objectAtIndex:2];
        if(callerStackSymbol) {
            NSMutableArray *callerStackSymbolDetailsArr = [[NSMutableArray alloc] initWithArray:[callerStackSymbol componentsSeparatedByString:@" "]];
            NSUInteger callerStackSymbolIndex = callerStackSymbolDetailsArr.count - 3;
            if (callerStackSymbolDetailsArr.count > callerStackSymbolIndex && [callerStackSymbolDetailsArr objectAtIndex:callerStackSymbolIndex]) {
                callerStackSymbol = [callerStackSymbolDetailsArr objectAtIndex:callerStackSymbolIndex];
                callerStackSymbol = [callerStackSymbol stringByReplacingOccurrencesOfString:@"]" withString:@""];
            }
        }
    }

    return callerStackSymbol;
}
Roy K answered 2019-09-10T09:03:39Z
4 votes

您可以将self作为函数的参数之一传递,然后获取调用者对象的类名:

+(void)log:(NSString*)data from:(id)sender{
    NSLog(@"[%@]: %@", NSStringFromClass([sender class]), data);
}

//...

-(void)myFunc{
    [LoggerClassName log:@"myFunc called" from:self];
}

这样您就可以传递任何可以帮助您确定问题所在的对象。

pckill answered 2019-09-10T09:04:10Z
2 votes

一个略微优化的@Roy Kronenfeld版本的精彩答案:

- (NSString *)findCallerMethod
{
    NSString *callerStackSymbol = nil;

    NSArray<NSString *> *callStackSymbols = [NSThread callStackSymbols];

    if (callStackSymbols.count >= 2)
    {
        callerStackSymbol = [callStackSymbols objectAtIndex:2];
        if (callerStackSymbol)
        {
            // Stack: 2   TerribleApp 0x000000010e450b1e -[TALocalDataManager startUp] + 46
            NSInteger idxDash = [callerStackSymbol rangeOfString:@"-" options:kNilOptions].location;
            NSInteger idxPlus = [callerStackSymbol rangeOfString:@"+" options:NSBackwardsSearch].location;

            if (idxDash != NSNotFound && idxPlus != NSNotFound)
            {
                NSRange range = NSMakeRange(idxDash, (idxPlus - idxDash - 1)); // -1 to remove the trailing space.
                callerStackSymbol = [callerStackSymbol substringWithRange:range];

                return callerStackSymbol;
            }
        }
    }

    return (callerStackSymbol) ?: @"Caller not found! :(";
}
Andrew answered 2019-09-10T09:04:37Z
2 votes

@ennuikiller

//Add this private instance method to the class you want to trace from
-(void)trace
{
  //Go back 2 frames to account for calling this helper method
  //If not using a helper method use 1
  NSArray* stack = [NSThread callStackSymbols];
  if (stack.count > 2)
    NSLog(@"Caller: %@", [stack objectAtIndex:2]);
}

//Add this line to the method you want to trace from
[self trace];

在输出窗口中,您将看到如下所示的内容。

来电:2 MyApp 0x0004e8ae - [IINClassroomInit buildMenu] + 86

您还可以解析此字符串以提取有关堆栈帧的更多数据。

2 = Thread id
My App = Your app name
0x0004e8ae = Memory address of caller
-[IINClassroomInit buildMenu] = Class and method name of caller
+86 = Number of bytes from the entry point of the caller that your method was called

它取自iOS中的Identify Calling Method。

DannyBios answered 2019-09-10T09:05:29Z
1 votes

Swift 4版@Geoff H回答复制和粘贴;]

let sourceString: String = Thread.callStackSymbols[1]
let separatorSet :CharacterSet = CharacterSet(charactersIn: " -[]+?.,")
var array = Array(sourceString.components(separatedBy: separatorSet))
array = array.filter { $0 != "" }

print("Stack: \(array[0])")
print("Framework:\(array[1])")
print("Memory Address:\(array[2])")
print("Class Caller:\(array[3])")
print("Method Caller:\(array[4])")
Andy Obusek answered 2019-09-10T09:05:55Z
0 votes

Swift 3版@Geoff H回答参考:

let sourceString: String = Thread.callStackSymbols[1]
let separatorSet: CharacterSet = CharacterSet(charactersIn: " -[]+?.,")
let array = NSMutableArray(array: sourceString.components(separatedBy: separatorSet))
array.remove("")

print("Stack: \(array[0])")
print("Framework:\(array[1])")
print("Memory Address:\(array[2])")
print("Class Caller:\(array[3])")
print("Method Caller:\(array[4])")
Carmelo Gallo answered 2019-09-10T09:06:20Z
translate from https://stackoverflow.com:/questions/1451342/objective-c-find-caller-of-method