0

If I have a method and class like this:

@implementation Animal
  -(void) move{
    id *object = [object that called move];
   }

@end

Say I have two other classes

@implementation C1
   ...
   [self.animal move]
   ...
@end

@implementation C2
  ...
  [self.animal move]
  ...
@end

Without passing the instance 'self' into move, is their some way to get access to self from move?

LDK
  • 2,555
  • 5
  • 27
  • 40
  • 1
    There is nothing like that in the language - what problem are you trying to solve? – Georg Fritzsche Jan 11 '12 at 20:13
  • 1
    possible duplicate of [How to find out who called a method?](http://stackoverflow.com/questions/1793999/how-to-find-out-who-called-a-method) also [How to find out who is the caller?](http://stackoverflow.com/questions/1373991/) and a nice answer from bbum at [Finding where a method was called from](http://stackoverflow.com/questions/1614208/finding-where-a-method-was-called-from). – jscs Jan 11 '12 at 20:16
  • Passing a 'sender' is a common idiom when achieving this. Think about a button, for example. You would add a handler to the button, and upon performing an action on the button, it calls the handler passing itself as the sender. – Jeremy Jan 11 '12 at 20:19
  • @GeorgFritzsche I have multiple windows, each with an instance of webkit. Within webkit I can access objective c objects. However, I have no way of knowing which window called and which webkit object called. – LDK Jan 11 '12 at 20:50
  • You know which window/webkit called if you have one scriptable instance per window. Better ask a new question on that specific problem though to solve this. – Georg Fritzsche Jan 11 '12 at 20:57

1 Answers1

3

You cannot do this in Objective-C, the only work around I could suggest is sending a reference of the sender when you message your class, such as:

@implementation Animal
  -(void) move:(id)sender{
    id *object = [object that called move];
   }

@end

Calling:

@implementation C1
   ...
   [self.animal move:self];
   ...
@end

@implementation C2
  ...
  [self.animal move:self];
  ...
@end

You can then use the isMemberOfClass: or isKindOfClass: to determine what type of object the sender is, isKindOfClass will return YES if the class in question is the class you send or a subclass of that. Whereas isMemberOfClass: will only return YES if the class you are messaging is an instance of the class you are sending it

example:

A * aClass; // is just A
[...]

B * bClass; // is a subclass of A
[...]

[aClass isMemberOfClass:[A class]]; // YES 
[bClass isMemberOfClass:[A class]]; // YES


[aClass isKindOfClass:[A class]]; // YES 
[bClass isKindOfClass:[A class]]; // NO
Daniel
  • 23,129
  • 12
  • 109
  • 154