0

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

user609906
  • 190
  • 3
  • 6
  • 12
  • 1
    You cannot cast `Human` to `Male` unless the objects themselves are instances of `Male`. – BoltClock Mar 02 '11 at 17:26
  • thanks boltClock, they are male objects, I also have female objects. human.sex can be either 1 or 0 depending on sex. So i know its male but is it the best way to cast the object? – user609906 Mar 02 '11 at 17:30
  • Objective-c being weak-typed (at least to my knowledge), casting is a niceness but nothing you need to do. It basically only helps to get rid of some compiler warnings. So yeah, i'd go down the casting route. – Blitz Mar 02 '11 at 17:58

2 Answers2

10

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;
    }
}
Kris Babic
  • 6,254
  • 1
  • 29
  • 18
0

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

jack
  • 731
  • 7
  • 8