Question

I've set up NSProxy, forwardInvocation etc to capture messages passed to an object - it all works fine.

What I want to also do is capture messages passed by self e.g.: [self doSomething] or self.myVal = 5;

It doesn't seem to work ... is this possible?

Was it helpful?

Solution

Sending a message to the proxy instance via self or another variable pointing to the proxy is no different. Under the hood each message dispatch is transformed to an objc_msgSend() function call, passing the address of the instance as the receiver, so it really doesn't matter if you use self or an "external variable" as long as each of them points to the same object.

Just to make sure, I have tested this by implementing an NSProxy subclass (TestProxy) forwarding messages to an NSObject subclass (TestObject). TestObject has one custom method printing out the description of the object:

@interface TestObject : NSObject
- (void)printDescription;
@end

The proxy has the following methods overridden (_theObject is the TestObject instance being proxied):

- (void)forwardInvocation:(NSInvocation *)anInvocation
{
    SEL selector = [anInvocation selector];

    if ([_testObject respondsToSelector:selector])
        [anInvocation invokeWithTarget:_testObject];
}

- (BOOL)respondsToSelector:(SEL)aSelector
{
    return [_testObject respondsToSelector:aSelector];
}

- (NSMethodSignature*)methodSignatureForSelector:(SEL)selector
{
    return [_testObject methodSignatureForSelector:selector];
}

Sending a printDescription message to the proxy via self correctly forwards the message call to _theObject:

[((id)self) printDescription];

If your problem was that the compiler gives you errors when you try to send a message directly to self without casting it to id, then my guess is that there is no cure for that. Since the compiler cannot detect the methods in the interface of the class of self (the proxy) and isn't smart enough to figure out that this is actually a proxy for another class, it will give you errors.

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