xcode ios 自定义 NSObject 转换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5171072/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 20:21:34  来源:igfitidea点击:

ios custom NSObject casting

iphoneobjective-cxcodeipadios

提问by user609906

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:

如果我有一个名为 Human 的自定义 NSObject,它有一个名为 Male 的子类,并且我有一个包含 Human 对象的名为 human 的数组。当迭代人类数组时,我可以投射对象,例如:

for (Human *human in humans) {
    Male *male = (Male *)human;
}

or is it better to create a method to initWithMale such as

或者最好创建一个方法来 initWithMale 例如

for (Human *human in humans) {
    Male *male = [[Male alloc] initWithMale:(Male *)human];
}

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?

从内存管理的角度来看,最好的方法是什么,或者这无关紧要?如果是后者,那么我将如何在我的 initWithMale 方法中管理它?

Thanks

谢谢

回答by Kris Babic

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:

这取决于您要实现的目标。如果 human 数组中的对象是 Human 的直接实例,则不能将它们强制转换为 Human 的任何子类,因为它们不属于该类型。如果这种情况是正确的,并且您正在尝试将 Human 转换为 Male,那么您将需要在 Male 类中创建一个 init 方法,该方法可以使用提供的 Human 启动一个新对象:

Male *male = [[Male alloc] initWithHuman: human];

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).

使用这种方法,您的 initWithHuman 方法要么需要保留传入的 Human 实例并引用其值,要么复制任何必要的数据。后一种方法可以添加到 Human 类本身,这将允许您使用 initWithHuman 方法启动任何子类(本质上,创建一个基本的复制功能)。

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:

如果 human 数组包含 Human 的子类,那么您可以将它们转换为正确的实例,但是,您应该首先检查它们是否是该实例。下面是一个例子:

for (Human *human in humans) {
    if ([human isKindOfClass:[Male class]]) {
        Male *male = (Male *) human;
    }
}

回答by Hyman

You don't need to cast an object of type id.

您不需要强制转换类型为 id 的对象。