这是我的场景。我有一个 A 类。在其实现中,我创建了 B 类型的对象并将 B 的委托(delegate)设置为 self(因此 B.delegate = self
在 A 类实现中的某处)。
并且类A有一个实例方法- (void)printThis;
现在在 B 的实现中,当我尝试执行 [delegate printThis];
时,它给了我这个错误:
“没有已知的选择器 printThis 实例方法”
当然这是我开启ARC的时候。上面的委托(delegate)模式过去在没有 ARC 的 iOS 4.x 中工作得很好。当我关闭 ARC 时它仍然如此。 ARC 与向代表传递消息有什么关系?
骨架代码:
啊啊
@class B;
@interface A: blah blah
{
B objB;
}
-(void) printThis;
上午
objB = [[B alloc] init];
objB.delegate = self;
- (void)printThis {
//doSomething
}
B.h
@interface B: blah blah
{
//id delegate; //used to be there, now I just property & synthesize
}
@property (nonatomic,weak) id delegate;
B.m
@synthesize delegate;
[delegate printThis]; //error with ARC ON, works with OFF
重要编辑:
请注意,这种情况时有发生。例如,我在 A 中有一些其他方法,如 printThat 等,它们可以正常工作。我对发生的事情一无所知!
最佳答案
需要在一个协议(protocol)中定义-printThis
,让A实现这个协议(protocol)。您还需要将委托(delegate)标记为符合此委托(delegate)。
即:
@protocol Printer <NSObject>
- (void)printThis;
@end
@interface A : NSObject <Printer>
//...
@end
@interface B : //...
@property (nonatomic, weak) id<Printer> delegate;
@end
ARC 需要了解方法调用的接口(interface),以便正确地正确管理内存。如果没有定义,它就会提示。
关于iphone - ARC 问题 - 无法将方法传递给委托(delegate)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7761087/