1

I am running a for-in loop over an NSMutableArray. There are instances of Class A in the array also out of those some are actually instances of its subclass B.

So If I only want members of subclass B, I am checking the class of each object I get in an if condition inside the loop body.

Is it possible that instead of writing something like this,

for(A* obj in collection){
    if([obj isKindOfClass:[B class]]){
        //take some action.
    }
}

I can do something like this?

   for(B* obj in collection){
      //take some action.
   }

Will I get the same result?

jscs
  • 63,694
  • 13
  • 151
  • 195
Amogh Talpallikar
  • 12,084
  • 13
  • 79
  • 135

2 Answers2

3

To my knowledge: no.

The for each loop will traverse every object in the collection, and I don't think you can specify that you only want to traverse a specific type.

To be clearer: The Object you specify: for (MyObject* obj){..} is a type-cast. So you're telling the object in the collection that they should be/behave as MyObject

Jesper
  • 460
  • 2
  • 10
  • 1
    You're right about iterating over *all* the objects, not just some. But you go off the rails at the end: the type of the pointer that you use in fast enumeration doesn't affect the objects in the collection at all. If there's an object that's an instance of NSString in the collection, the fact that `obj` is of type MyObject* doesn't make the string act like a MyObject. Instead, you'll get a run time error when you call a MyObject method on that string, which is why the OP tests the type of the object first. – Caleb Feb 15 '12 at 08:05
  • You're absolutely right. That was what I was trying to say, but apparently I didn't do well ;-) – Jesper Feb 15 '12 at 13:40
  • I figured you did -- just wanted to make sure it was clear for future readers. Cheers. – Caleb Feb 15 '12 at 14:35
2

Can I do something like this...

No, you can't use the type of the index variable in fast enumeration to select only some of the objects in the collection. If the collection contains different types of objects, you'll have to test each object first. Instead of testing class membership, though, it's often nicer to test for the behavior you're looking for with -respondsToSelector: or -conformsToProtocol instead of -isKindOfClass:.

Caleb
  • 124,013
  • 19
  • 183
  • 272