问题描述
如果我有一个名为Human的自定义NSObject,它有一个名为Male的子类,我有一个名为human的数组,包含Human对象。当迭代人类数组时,我可以投射对象,例如:
If I have a custom NSObject called Human which has a subclass called Male and I have an array called humans containing Human objects. When iterating over the humans array can I cast the object such as:
for (Human *human in humans) {
Male *male = (Male *)human;
}
或创建initWithMale方法更好,例如
or is it better to create a method to initWithMale such as
for (Human *human in humans) {
Male *male = [[Male alloc] initWithMale:(Male *)human];
}
从内存管理的角度来看,最好的方法是什么?没关系?如果是后者那么我将如何在我的initWithMale方法中管理它?
What would be the best approach from a memory management point of view or would it not matter? If it is the latter then how would I manage this in my initWithMale method?
谢谢
推荐答案
这取决于你想要完成的事情。如果人类数组中的对象是Human的直接实例,那么您不能将它们转换为Human的任何子类,因为它们不属于该类型。如果这种情况是正确的并且您正在尝试将Human转换为Male,那么您将需要在Male类中创建一个init方法,该方法可以使用提供的Human启动一个新对象:
It depends on what you are trying to accomplish. If the objects in the humans array are direct instances of Human, then you cannot cast them to any subclass of Human as they are not of that type. If this scenario is correct and you are trying to convert a Human into a Male, then you will need to create a init method in the Male class that can initiate a new object using a supplied Human:
Male *male = [[Male alloc] initWithHuman: human];
使用这种方法,你的initWithHuman方法需要保留传入的Human实例并引用其值,或复制任何必要的数据。后一种方法可以添加到Human类本身,这将允许您使用initWithHuman方法启动任何子类(实质上,创建一个基本的复制函数)。
With this approach, your initWithHuman method would either need to retain the passed in Human instance and reference its values, or copy any necessary data. The later approach could be added to the Human class itself and that would allow you to initiate any subclass using the initWithHuman method (in essence, creating a basic copy function).
如果人类数组包含Human的子类,那么您可以将它们转换为正确的实例,但是,您应该首先检查它们是否是该实例。这是一个例子:
If the humans array contains subclasses of Human, then you can cast them to the correct instance, however, you should check to see if they are that instance first. Here is an example:
for (Human *human in humans) {
if ([human isKindOfClass:[Male class]]) {
Male *male = (Male *) human;
}
}
这篇关于ios定制NSObject铸造的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!