ARC和消息转发

时间:2013-10-12 18:40:12

标签: iphone objective-c xcode automatic-ref-counting message-forwarding

我尝试实现Message Forwarding。 Xcode 5,ARC是ON,新的默认iPhone项目。 I read a documentation here

我的项目中有两个自定义类:HelloWorld

#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

世界很简单:

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

#import "World.h"
@implementation World

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

@end

在我的AppDelegate中,我写了三个简单的行:

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

编译器给我一个错误:AppDelegate.m:23:9: No visible @interface for 'Hello' declares the selector 'spin'并且没有构建项目。当我重新输入时:[me performSelector:@selector(spin)]; - 它运行正常。

代码[me spin]仅在ARC关闭时有效(但编译器会生成警告AppDelegate.m:23:9: 'Hello' may not respond to 'spin')。

我的问题:为什么?如何使用ARC进行邮件转发?

1 个答案:

答案 0 :(得分:0)

尝试将我声明为id:

 id me = [[Hello alloc] init];
 [me say];
 [me spin];
相关问题