---
title: "Print calling function"
slug: print-calling-function
section: tech
date: 2015-05-19T10:25:00.000Z
canonical: https://roland.leth.ro/blog/tech/print-calling-function
---

Sometimes you need to find out what called a method. [StackOverflow](http://stackoverflow.com/questions/1451342/objective-c-find-caller-of-method) helped me find an answer:

```swift
public func printCallingFunction() {
  let syms = Thread.callStackSymbols()
	
  if !syms.isEmpty {
    var sourceString = syms[2] as? String ?? ""
    var separatorSet = CharacterSet(characters: " -[]+?.,")
    var array = sourceString
      .componentsSeparated(by: separatorSet)
      .filter() { !$0.isEmpty }
  }

  // 3 is the class, 4 is the method.
  print("--- \(array[3]) - \(array[4])");
}
```

There's also this approach, but I don't really like it:

```objc
#include <execinfo.h>

void *addr[2];
int nframes = backtrace(addr, sizeof(addr)/sizeof(*addr));
if (nframes > 1) {
  char **syms = backtrace_symbols(addr, nframes);
  NSLog(@"%s: caller: %s", __func__, syms[1]);
  free(syms);
} else {
  NSLog(@"%s: *** Failed to generate backtrace.", __func__);
}
```
