0

I have a function - myFunc() in class A. There are multiple other classes calling this function.

How will I be able to find out which class is calling myFunc() at a particular instance?

Would someone be able to help me with this?

learner2010
  • 4,157
  • 5
  • 43
  • 68
  • possible duplicate of [Objective C find caller of method](http://stackoverflow.com/questions/1451342/objective-c-find-caller-of-method) – jscs Jun 20 '12 at 20:19

2 Answers2

1

Use the Visitor pattern

  1. Have each of the calling classes implement a common protocol that defines the interface of the behavior you are looking to achieve.
  2. Add the protocol as a parameter to myFunc.
  3. When calling myFunc(), specify self as the parameter.
  4. myFunc can now invoke any of the protocol methods without knowing about the other specific classes.

This way you adhere to the concepts of encapsulation.

Peter Cetinski
  • 2,328
  • 14
  • 8
1

Conceptually, this information is available in the stack, though it isn't easy to get to. Most solutions would involve creating an exception in order to capture the stack trace, and then reading the trace. I haven't tried this, but it might work:

void myFunc()
{
    NSArray *stack = [NSThread callStackSymbols];
    // I have no idea if the current function call is at the 0 or last position
    // of the array. Experiment here!
}

Pertinent documentation: NSThread Class Reference

Note that if you want your function to behave differently depending on who is calling, DO NOT DO THIS. It's fragile (there are no guarantees about whether the format of what callStackSymbols returns will change).

It's better to simply pass a parameter into your function. If you're dealing with a C-function callback API, there is typically a void * "context" or "info" parameter that you can use to pass in an arbitrary pointer. This could be a pointer to your object.

benzado
  • 82,288
  • 22
  • 110
  • 138