【问题标题】:ARC and Message Forwarding [duplicate]ARC 和消息转发 [重复]
【发布时间】:2013-10-12 18:40:11
【问题描述】:

我尝试实现消息转发。 Xcode 5,ARC 开启,新的默认 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 用于消息转发?

【问题讨论】:

  • 可能是……但我认为那里没有答案。
  • 所以我不能再像[me spin];这样发送消息了?
  • 是的,这就是我在回答该问题时试图解释的内容。

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


【解决方案1】:

尝试将我声明为 id:

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

【讨论】:

  • 如果您在该源文件中包含“World.h”,这将起作用,以便编译器知道有一个spin 方法。
  • 不起作用AppDelegate.m:23:5: Multiple methods named 'spin' found with mismatched result, parameter type or attributes
  • 是的,这只有在只有一个名为 spin 的方法(或者更多,但签名相同)时才有效。
猜你喜欢
  • 2014-09-04
  • 2013-10-31
  • 2013-03-11
  • 2014-07-23
  • 1970-01-01
  • 1970-01-01
  • 2016-12-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多