ARC and Message Forwarding

221 Views Asked by At

I tried to implement Message Forwarding. Xcode 5, ARC is ON, new default iPhone project. I read a documentation here

I have two custom classes in my project: Hello and World.

#import <Foundation/Foundation.h>
@interface Hello : NSObject
    - (void) say;
@end

#import "Hello.h"
#import "World.h"

@implementation Hello

- (void) say {
    NSLog(@"hello!");
}

-(void)forwardInvocation:(NSInvocation *)invocation {
    NSLog(@"forward invocation");
    World *w = [[World alloc] init];
    if ([w respondsToSelector:[invocation selector]]) {
        [invocation invokeWithTarget:w];
    } else {
        [self doesNotRecognizeSelector: [invocation selector]];
    }
}

-(NSMethodSignature*)methodSignatureForSelector:(SEL)selector {
    NSLog(@"method signature");    
    NSMethodSignature *signature = [super methodSignatureForSelector:selector];
    if (! signature) {
        World *w = [[World alloc] init];
        signature = [w methodSignatureForSelector:selector];
    }
    return signature;
}

@end

World is simple:

#import <Foundation/Foundation.h>
@interface World : NSObject
    - (void) spin;
@end

#import "World.h"
@implementation World

- (void) spin {
    NSLog(@"spin around");
}

@end

In my AppDelegate i wrote three simple lines:

Hello  *me = [[Hello alloc] init];
[me say];
[me spin];

And compiler give me an error: AppDelegate.m:23:9: No visible @interface for 'Hello' declares the selector 'spin' and doesn't build a project. When I retype it: [me performSelector:@selector(spin)]; - it works fine.

Code [me spin] works when ARC is OFF only (but compiler generates a warning AppDelegate.m:23:9: 'Hello' may not respond to 'spin').

My questions: why? and How can I use ARC with message forwarding?

1

There are 1 best solutions below

3
vkurchatkin On

Try declaring me as id:

 id me = [[Hello alloc] init];
 [me say];
 [me spin];