views:

58

answers:

2

I have an NSArray that contains two types of objects. Lets call them Apple and Orange.

Apple *myApple = [self.searchQueryResults objectAtIndex:indexPath.row];

When I am building my cell's I don't know what type is in my array, apples or oranges. How can I use the generic id type to store the object, and then cast appropriately?

+2  A: 

You can use isKindOfClass:(Class)aClass to test the class type:

if ([myObject isKindOfClass:[Apple class]])
   // do stuff

I'm not sure why you think you have to cast though. NSArray doesn't care what type of object you store in it, so when you pull it out, it'll still be the same object. But if you want you could still cast by doing something like

Apple *myApple = (Apple *)myObject;

Anyways, knowing the type of class it is should be enough for you to take appropriate action, since it's my understanding that you're showing both types in the same table, all you really need to do is appropriately display their different properties.

Jorge Israel Peña
You don't need to cast, but if you use object.property to use an object's properties, you need to cast it to the appropriate type. Otherwise, you can just use [object property] and [object setProperty:x] to access a property.
lucius
@lucius: which is why you should do that anyway! :P
chpwn
+2  A: 

Don't mix types of classes in an NSArray.

You can do it, you can run checks for the type - but it's a really bad idea, UNLESS they are both part of the same subclass tree (say, both derivatives of Fruit). Then at least something looking in there can assume what kind of Fruit it might be, and check for particulars.

Basically you will save yourself a lot of headaches if you don't mix types in container classes, when somewhere down the road some bit of code figures for some reason there are only Apples in there but someone throws in a Pear. Then, BOOM!

Kendall Helmstetter Gelner
I think a better way to state this is: Don't mix types in a container unless you intend to use them polymorphically in some fashion. I can think of several ways to use objects of different types polymorphically when they share neither a base class nor a protocol. Overall, though, I share your opinion. (By the way, I'm not necessarily speaking of formal polymorphism.)
Gregory Higley
That's a much better way to put what I was trying to say, though I was trying to keep it simple... what you said is much more accurate and the way I try to keep things.
Kendall Helmstetter Gelner