让我们考虑一个具有高度自定义或复杂 View 的应用程序。
我们将有一种特定类型的 View Controller 向特定类型的 UIView 发送方法,其中 UIView 本身由许多其他 View 组成。
View 应该有一个丰富的、特定领域的接口(interface),允许 Controller 在它和类似的丰富模型之间充当一个薄的“胶水”层。
所以我们重写 Controller 的 View 属性,如下所示:
@interface PlaybackViewController : UIViewController<StageLayoutDelegate, ControlPanelDelegate>
{
NSMutableArray* _sections;
LightingMode _lightingMode;
}
@property (nonatomic, strong) PlaybackView* view; // <------ Specific type of view
#pragma mark - injected
@property (nonatomic, strong) id<OscClient> oscClient;
@property (nonatomic, strong) AbstractStageLayoutView* stageLayoutView;
@end
Ovverriding 比定义另一个访问器更有意义,而且我可以将消息发送到特定类型的 UIView 而无需强制转换。
问题:唯一的问题是它会导致编译器警告:
属性类型“PlaybackView *”与从“UIViewController”继承的类型“UIView *”不兼容
. .我喜欢构建没有任何警告的代码。这样,一个有效的警告就不会被隐藏在其他警告中而被遗漏。
问题:
- 有没有办法抑制这个特殊警告?
- 为什么这是默认设置的一部分,而大多数现代 OO 语言都乐于允许覆盖子类中的属性或方法,以便它返回父类(super class)中声明的类型的更具体的子类?
最佳答案
这里的问题不是属性的覆盖,而是使用类类型的前向声明。
所以这个...
@class PlaybackView;
@interface PlaybackViewController : UIViewController
@property (nonatomic, strong) PlaybackView* view;
@end
会给你提到的警告,因为编译器不知道 PlaybackView
的继承层次。 UIViewController
有一个契约(Contract),从它的 view
属性中提供一个 UIView
它告诉你它认为 PlaybackView
不是 UIView
这里的简单解决方案是使用 #import
来让编译器充分了解 PlaybackView
...
#import "PlaybackView.h"
@interface PlaybackViewController : UIViewController
@property (nonatomic, strong) PlaybackView* view;
@end
或者(但非常糟糕的形式,因为 PCH 是一个优化功能,不应该管理依赖项)是将 #import "PlaybackView.h"
添加到您的项目 PCH
关于ios - 用特定类型覆盖 UIViewController.view,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14698935/