如何在Objective-C中正确子类化委托属性? [英] How to properly subclass a delegate property in Objective-C?

查看:118
本文介绍了如何在Objective-C中正确子类化委托属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在对类进行子类化时,我还希望子类的父类的子类,因为子类现在具有其他功能。这样做的最佳方法是什么?如果我只是在子类中使用相同的名称声明另一个委托属性,我会收到警告属性类型'id'与继承自'ParentClass'的类型'id'不兼容

In subclassing a class, I want to also subclass a delegate of the parent class given that the subclass now has additional functionality. What's the best way to go about doing this? If I just declare another delegate property in the subclass with the same name I would get a warning "Property type 'id' is incompatible with type 'id' inherited from 'ParentClass'

推荐答案

鉴于此示例产生警告:

// Class A
@protocol ClassADelegete;

@interface ClassA : NSObject
@property (nonatomic, weak) id<ClassADelegete> delegate;
@end

@protocol ClassADelegete <NSObject>
- (void)classADidSomethingInteresting:(ClassA *)classA;
@end

// Class B
@protocol ClassBDelegete;

@interface ClassB : ClassA
@property (nonatomic, weak) id<ClassBDelegete> delegate; // Warning here
@end

@protocol ClassBDelegete <ClassADelegete>
- (void)classBDidSomethingElse:(ClassB *)classB;
@end

删除警告的两个解决方案是。

Two solutions that remove the warning are.

1)在子类中,将协议定义放在类定义之前。这就是 UITableView.h 中的 UITableViewDelegate

1) In the subclass, place the protocol definition before the class definition. This is what UITableViewDelegate in UITableView.h does:

// Class B
@class ClassB;

@protocol ClassBDelegete <ClassADelegete>
- (void)classBDidSomethingElse:(ClassB *)classB;
@end

@interface ClassB : ClassA
@property (nonatomic, weak) id<ClassBDelegete> delegate;
@end

2)在子类中,添加原始协议和新协议:

2) In the subclass, add the original protocol alongside the new one:

// Class B
@protocol ClassBDelegete;

@interface ClassB : ClassA
@property (nonatomic, weak) id<ClassADelegete, ClassBDelegete> delegate;
@end

@protocol ClassBDelegete <ClassADelegete>
- (void)classBDidSomethingElse:(ClassB *)classB;
@end

我认为(1)就像苹果这样做,Option( 2)删除警告,但我没有编译并以这种方式运行任何设置。

I assume (1) works as Apple do it this way, Option (2) removes the warning but I haven't compiled and run anything setup this way.

这篇关于如何在Objective-C中正确子类化委托属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆