如何将超类属性复制到子类?
假设我有两个类,如下所示:
Car
{
NSInteger wheels;
NSInteger bumpers;
}
+ (Car *)carWithData:(NSDictionary *)carData;
Lexus : Car
{
GPS *navigation;
}
+ (Lexus *)carWithData:(NSDictionary *)carData;
carWithData:
是一个简单的辅助方法,它创建一个 Car
实例,并用 carData
中的变量填充。雷克萨斯的版本还会设置导航
数据。
如果不复制 Car
的代码,雷克萨斯的 carWithData
会是什么样子?
Let's say I have two Classes like so:
Car
{
NSInteger wheels;
NSInteger bumpers;
}
+ (Car *)carWithData:(NSDictionary *)carData;
Lexus : Car
{
GPS *navigation;
}
+ (Lexus *)carWithData:(NSDictionary *)carData;
carWithData:
is a simple helper method that creates an instance of Car
populated with variables from carData
. Lexus' version would also set the navigation
data.
How would Lexus' carWithData
look like without duplicating code from Car
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是通过在 init 方法中调用
super
的init...
实现来完成的:另请注意,
initWith...
和carWith ...
方法返回id
,而不是Car
或Lexus
。您的代码设置方式最终会出现转换问题,其中
[Lexus carWithData:dataDict]
确实返回类Lexus
的对象,但编译器不知道关于它,因为它需要一辆汽车
。This is accomplished by calling
super
's implementation ofinit…
in the init method:Also note that both the
initWith…
andcarWith…
methods returnid
, notCar
orLexus
.The way your code is set up you end up with casting problems, where
[Lexus carWithData:dataDict]
does return an object of classLexus
, but the compiler doesn't know about it, as it expects aCar
.您不会使用不同的签名来定义方法,例如:
您应该使用
子类的实现将如下所示
You would not define the methods with different signatures like:
you should instead use
The implementation of the subclass would then look like
这是我的解决方案:
因此,当您调用
[Lexus carWithCarData:myData]
时,它最终会调用Lexus
的init
方法,而不是汽车
的。Here would be my solution:
So, when you call
[Lexus carWithCarData:myData]
it ends up calling theLexus
'sinit
method, not theCar
's.还有另一种更通用的方法,即使用 NSCoding 协议和 NSKeyedArchiver。
如果您想要复制到子类中的对象实现了 NSCoding 协议(许多基于 NS... 的类都是这种情况),则可以使用以下完全合法且安全的技巧:
There's another way, which is more generic, by using the
NSCoding
protocol andNSKeyedArchiver
.If the object you want to copy into a subclass of yours implements the
NSCoding
protocol, which is the case for many NS... based classes, the following totally legal and safe trick can be used: