Question

I have an object (A) that needs to work as a proxy to an other object. there is also a condition that when verified should make the object work as nil.

I've implemented:

-(void)forwardInvocation:(NSInvocation *)anInvocation
{
    if (condition)
        [anInvocation invokeWithTarget:self.object];
    else
        [anInvocation invokeWithTarget:nil];
}

but it's not enough. when the condition is satisfied and a method is called on A unrecognized selector sent to instance is raised.

Was it helpful?

Solution

From the documentation on invoke in NSInvocation's class reference:

You must set the receiver’s target, selector, and argument values before calling this method.

If you haven't set target (or have set it to nil, which is basically the same thing), you shouldn't be invoking the invocation. If you want to mimic the behaviour of sending a message to nil, you can just return 0/nil - this is the default behaviour of objc_msgSend if the target is nil. If you're interested in seeing why this works, you can have a look here for an overview of objc_msgSend's implementation (fair warning, it's all in assembly).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top