Mailing Lists: Apple Mailing Lists
Image of Mac OS face in stamp
Re: Who called.
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Who called.



On Wed, Oct 20, 2010 at 07:16, Sandro Noël <email@hidden> wrote:
> How would i go about adding a stack trace to that nsLog like this.
>     #define ENTERING() NSLog(@"[%@ %s]-Called By :%@", [self class], _cmd,
> caller)

Hi,

I took a few liberties with your code, which I shall outline for clarity.

1. I gave the method a long name. Otherwise, as a category on
NSObject, it may come in conflict with methods of so many other
classes.
2. We have been told on this mailing list, time and time again, never
to assume that SEL* is equivalent to char*. I therefore wrapped _cmd
in sel_getName, which does return const char*.
3. I had to go one step further in the backtrace on my 32-bit 10.6
machine to obtain the actual caller. Your mileage may vary; adjust
back if needed.
4. You never dealloc the NSString you alloc in the backtrace-searching
function. I replaced the alloc-init with the shorthand (which throws
it into a NSAutoreleasePool) to prevent a leak.
5. initWithCString and stringWithCString use the undefined System
Encoding and are therefore deprecated. I stringWithUTF8String as a
replacement, which shouldn't be a problem because selectors are
normally Low ASCII anyway.

/* put this into a .h file */

#import <Foundation/Foundation.h>
#include <objc/runtime.h>	/* for sel_getName */

@interface NSObject(CallerFromBacktrace)

- (NSString *)_hopefully_unused_prefix_callerFromBacktrace;

@end

#define ENTERING() NSLog(@"[%@ %s]-Called By: %@", [self class],
sel_getName(_cmd), [self
_hopefully_unused_prefix_callerFromBacktrace])

/* put this into a .m file */
#import "NameOfTheHFileYouCreatedOneStepAgo.h"
#include <execinfo.h>

@implementation NSObject(CallerFromBacktrace)

- (NSString *)_hopefully_unused_prefix_callerFromBacktrace
{
	void * callstack[3];
	int frames = backtrace(callstack, 3);
	char ** strs = backtrace_symbols(callstack, frames);
	NSString * caller = nil;

	if (frames > 2)
	{
		caller = [NSString stringWithUTF8String: strs[2]];
	}

	free(strs);
	return caller;
}

@end

Tested on 10.6 with a nauseatingly bleeding-edge version of Clang.

Cheers,
~~ Ondra
 _______________________________________________
Do not post admin requests to the list. They will be ignored.
Objc-language mailing list      (email@hidden)
Help/Unsubscribe/Update your Subscription:

This email sent to email@hidden

References: 
 >Who called. (From: Sandro Noël <email@hidden>)
 >Re: Who called. (From: "Stephen J. Butler" <email@hidden>)
 >Re: Who called. (From: Sandro Noël <email@hidden>)



Visit the Apple Store online or at retail locations.
1-800-MY-APPLE

Contact Apple | Terms of Use | Privacy Policy

Copyright © 2011 Apple Inc. All rights reserved.