How to get Caller Name class in C object using inheritance?

I have a base class BaseClass. Many classes derived from BaseClass, namely SubClass1, SubClass2 and SubClass3.

@interface BaseClass: NSObject{ } -(void)configure; @end; @implementation -(void)configure{ NSLog(@"This needs to log from which sub class this method was called"); } @end; 

The configure method can be called by instantiating subclasses or in their implementations.

I need to know from which subclass this method was called.

Is it possible?

+7
source share
4 answers

Not. Methods have no way of knowing from which other object method they are being called. There is not even a notion of identity of the caller. Methods can be called from a C function, where there is no caller at all.

I need to know from which subclass this method was called.

However, you probably just want to find out which (derived) class the object is from:

 NSLog(@"My class: %@", NSStringFromClass([self class])); 

2014 Addendum: There is a gnu __builtin_return_address extension that can be used for this purpose. Mike Ash shows how to use it to retrieve the name of the caller’s name (see Caller Check). I still think the whole approach is a bit fragile and should only be used for debugging.

+13
source

The accepted answer is incorrect.

 NSArray *stack = [NSThread callStackSymbols]; NSString *methodThatDidLogging = [stack objectAtIndex:1]; 

You can easily parse this string to get the name of the class and method of the caller.

I use this in my custom log to print the class and method logging the message

Greetings

+2
source

The answer depends on whether you want a class or instance and whether it is the sender or receiver of the message that interests you.

For the receiver class, you can use the -class method (declared in NSObject ), i.e.

 -(void)configure { NSLog(@"This logs from which sub class this method was called"); NSLog(@"Class of this object is %@", [self class]); } 

The recipient instance is, of course, just self . If the sender you are interested in, you cannot receive it automatically, but you can pass it as an argument. This way you will have something like

 -(void)configure:(id)sender { NSLog(@"This logs from which sub class this method was called"); NSLog(@"Class of object that called this method is %@", [sender class]); } 
+1
source

You can also use:

 const char* class_getName(Class cls) 

defined in <objc / runtime.h>

+1
source

All Articles