3

I'm struggling to forward a class method through a facade class.

To clarify, I'm overriding all the following methods:

-(NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector
-(void)forwardInvocation:(NSInvocation *)anInvocation
+(BOOL)instancesRespondToSelector:(SEL)aSelector
+(NSMethodSignature *)instanceMethodSignatureForSelector:(SEL)aSelector
+(IMP)instanceMethodForSelector:(SEL)aSelector
+(BOOL)resolveClassMethod:(SEL)sel
+(BOOL)resolveInstanceMethod:(SEL)sel

.. and yet, for the class method, the only one to be called is +resolveClassMethod. From there, I immediately get an unrecognized selector exception regardless of whether I return YES or NO.

What's going on?
Does class message forwarding work differently to instance message forwarding?
Similarly, why isn't there a +forwardInvocation class method?

Any help would be greatly appreciated.

newacct
  • 119,665
  • 29
  • 163
  • 224

1 Answers1

6

So you already know that to make an object do forwardInvocation for instance methods, you have to implement the instance methods -forwardInvocation: and -methodSignatureForSelector: (the others are unnecessary). Well, class methods are just methods on the class object. Classes are objects and work like any other objects, and support all the instance methods of the root class (NSObject in this case).

The Objective-C runtime doesn't care that an object is a class object or non-class object. The message forwarding mechanism is the same. So when you send a message to an object, whatever it is, and it can't find it, it just looks for the forwardInvocation: and methodSignatureForSelector: methods on the object. So you need to have these methods on your class object.

i.e. implement the class methods +forwardInvocation: and +methodSignatureForSelector:

newacct
  • 119,665
  • 29
  • 163
  • 224
  • I can't see `+forwardInvocation:` method in NSObject protocol – Julian Jun 27 '14 at 12:32
  • @JulianKról: `-forwardInvocation:` is in the NSObject class. – newacct Jun 27 '14 at 18:17
  • fine but you mentioned in the answer `+forwardInvocation`, thats why I commented – Julian Jun 27 '14 at 18:32
  • @JulianKról: All instance methods of the root class (NSObject is a root class) are automatically inherited as class methods of the root class (and thus as class methods of all other classes inheriting from it). This is because the superclass of the root class's metaclass is the root class itself. – newacct Jun 27 '14 at 18:35