开发者

How to use id variable in objective-c?

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?


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.


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!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜