iphone - ARC 问题 - 无法将方法传递给委托(delegate)?

标签 iphone objective-c ios automatic-ref-counting

这是我的场景。我有一个 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/

相关文章:

iphone - 如何知道 UIkeyboard 是否出现在 iOS 中?

iphone - 将 Core Data For Storage 用于现有的 Iphone 项目?

ios - 在UINavigation Controller中获取UITabBarController中View Controller的currentViewController

ios - 子类化 UIPageViewController,但是当我将 [[alloc] init] 的结果分配给自己时,我收到警告。为什么?

ios - 删除 Storyboard并使用 .xib 启动应用程序

iphone - 在 iAd 和 adSense 之间,您有何建议

iphone - 带滚动的页面控制图像

objective-c - 一些初学 Objective-C/iPhone 的问题

ios - 如何在Swift 3.0中使用coreLocation框架创建20多个地理围栏

ios - 以编程方式更改 UIView 元素的所有颜色的优化方法