1

我試圖實現消息轉發。 Xcode 5,ARC是ON,新的默認iPhone項目。 I read a documentation hereARC和消息轉發

我在我的項目中有兩個自定義類: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與郵件轉發?

+0

可能...但沒有答案,我想。 –

+0

所以我不能使用發送消息像'[我旋轉];'? –

+1

是的,這正是我在回答這個問題時試圖解釋的。 –

回答

0

嘗試宣告我的ID:

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

如果您在該源文件中包含「World.h」,那麼這將起作用,以便編譯器*知道*有一個「旋轉」方法。 –

+0

不起作用'AppDelegate.m:23:5:找到多個名爲'spin'的方法,結果不匹配,參數類型或屬性' –

+0

是的,這隻能在只有一個名爲'spin'的方法更多,但具有相同的簽名)。 – vkurchatkin