[英]Changing class of a variable when subclassing in Objective-C
I have a simple class defined, called 'PostView', which subclasses UIView. 我定义了一个简单的类,称为“ PostView”,该类继承了UIView。 Inside that class I have defined an 'item' in the implementation, which is an instance of 'Post'.
在该类内部,我在实现中定义了一个“项目”,它是“ Post”的一个实例。
@interface PostView : UIView <UIScrollViewDelegate> {
Post *item;
}
This works fine for me, but a problem occurs when I subclass it: 'PostPhotoView'. 这对我来说很好用,但是当我将其子类化时会出现问题:“ PostPhotoView”。 The 'item' variable now needs to be a 'PostPhoto' instance, but I'm not sure how I can go about doing this without defining 'item' in each subclass, which sound a bit repetitive and dirty..
现在,“ item”变量必须是“ PostPhoto”实例,但是我不确定如何在每个子类中都没有定义“ item”的情况下进行此操作,这听起来有些重复和肮脏。
Ideally I want to do this: 理想情况下,我想这样做:
@interface PostPhotoView : PostView {
PostPhoto *item;
}
But obviously I cannot redefine the variable. 但是显然我无法重新定义变量。 Maybe I am going about this in the wrong way?
也许我会以错误的方式进行此操作?
Thanks. 谢谢。
There are two ways to deal with this: 有两种方法可以解决此问题:
PostPhoto *theItem = (PostPhoto *)self.item
PostPhoto *theItem = (PostPhoto *)self.item
id
, so you can do PostPhoto *theItem = self.item
. id
类型,以便可以执行PostPhoto *theItem = self.item
。 For completeness, if you're using a declared property of type id
, you might also want to check the value in the setter: NSParameterAssert([theItem isKindOfClass:[Post class]])
. NSParameterAssert([theItem isKindOfClass:[Post class]])
,如果您使用id
类型的声明属性,则可能还需要检查setter中的值: NSParameterAssert([theItem isKindOfClass:[Post class]])
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.