我試圖實現消息轉發。 Xcode 5,ARC是ON,新的默認iPhone項目。 I read a documentation hereARC和消息轉發
我在我的項目中有兩個自定義類:Hello
和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
世界很簡單:
#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與郵件轉發?
可能...但沒有答案,我想。 –
所以我不能使用發送消息像'[我旋轉];'? –
是的,這正是我在回答這個問題時試圖解釋的。 –