Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Objective C determine the caller object reference at runtime (reflection)? [duplicate]

As far as I understand Objective C is a much more dynamic language than C# or Java. In C# you can only know the class of the caller object (using stacktrace) but not the instance reference of the caller itself.

Is Objective C more capable for this ?

Update: I looked the other post here How can I determine the "caller" of my method in Objective-C?. As far as I understand it only gives Class Name. I insist that I'm not interested only by class name but by getting a ref to the caller instance itself.

like image 382
user310291 Avatar asked Jan 28 '12 14:01

user310291


3 Answers

This has already been answered here:

How can I determine the "caller" of my method in Objective-C?

The answer's not particularly pretty though. It looks like there's no simple, reliable way to do it other than hunting through the stack, which might be OS version or platform dependent.

Why exactly did you want to do this? Perhaps there's another solution to your problem.

like image 173
Nick Lockwood Avatar answered Nov 19 '22 14:11

Nick Lockwood


As far as I know you can't get even the class of the caller. All method calls in Objective-C are routed through objc_msgSend(), which takes the receiver, a selector and the parameters of the method as parameters.

The receiver will be self and the selector _cmd. The caller isn't involved in the method call. You can only go back the stack trace in order to know where the method has been called.

like image 37
Fabian Kreiser Avatar answered Nov 19 '22 13:11

Fabian Kreiser


I think this could be a start: NSLog(@"%@", [NSThread callStackSymbols]);.

Although, I think you need to see this thread first : How to find out who called a method?

Also NSThread Documentation :)

like image 3
nacho4d Avatar answered Nov 19 '22 13:11

nacho4d