1

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.

3
  • 1
    If the target is nil, why invoke at all?
    – CodaFi
    Commented Mar 23, 2014 at 4:32
  • basically if a is my proxy. I want c = [a methodB] be either [a.object methodB] or nil, depending on condition. I don't want the application to crash.
    – lucaconlaq
    Commented Mar 23, 2014 at 23:17
  • Would NSNull in place of nil work for your use case?
    – quellish
    Commented Mar 26, 2014 at 23:34

1 Answer 1

0
+50

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).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.