Reputation: 190
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;
}
or is it better to create a method to initWithMale such as
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?
Thanks
Upvotes: 0
Views: 14388
Reputation: 6304
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];
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).
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;
}
}
Upvotes: 10