FUJI Goro
FUJI Goro

Reputation: 889

How can I get the filename and line number of caller function in ObjC?

As many scripting languages has caller(), I'd like to get caller's information in ObjC methods. Especially, I need it in the dealloc method, which is automatically called by the compiler so I could not pass any arguments to it.

Because ObjC exceptions have stacktrace, the caller information exists somewhere, I guess. How can I get the information without throwing exceptions?

-(void)dealloc {
  // get caller's information and NSLog() it here!
}

Upvotes: 2

Views: 807

Answers (3)

Catfish_Man
Catfish_Man

Reputation: 41801

Have you considered using dtrace (http://www.mactech.com/articles/mactech/Vol.23/23.11/ExploringLeopardwithDTrace/index.html has some info, googling for "mac dtrace" has much more) to introspect your app from the outside, rather than adding things inside it? You can get a ton of information that way, and if it's not enough, you can even add custom static probes inside your app to gather more.

Upvotes: 2

Carl Norum
Carl Norum

Reputation: 224944

You can get the information you want from the backtrace(3) && backtrace_symbols(3) C functions. You might need some jiggery pokery to make it look good for an Objective-C case.

Edit: I take it back - backtrace_symbols gave beautiful output here for an Objective-C test program:

0   example           0x0000000109274c77 +[TestClass classMethod] + 55
1   example           0x0000000109274cee -[TestClass instanceMethod] + 46
2   example           0x0000000109274dec main + 140
3   libdyld.dylib     0x00007fff914c37e1 start + 0

0   example           0x0000000109274c77 +[TestClass classMethod] + 55
1   example           0x0000000109274d36 -[TestClass dealloc] + 54
2   example           0x0000000109274e19 main + 185
3   libdyld.dylib     0x00007fff914c37e1 start + 0

I put the backtrace* calls in classMethod and called it from instanceMethod and from dealloc. Seems to work in both cases, no problem.

Upvotes: 2

Lluís
Lluís

Reputation: 588

Using self and _cmd?

NSLog(@"%@", self);

Upvotes: -2

Related Questions