Looping through an array of dynamic objects

1.2k views Asked by At

I'm not really sure exactly how to describe what I want to do - the best I can do is provide some code as an example:

- (void) doStuffInLoopForDataArray:(NSArray *)arr forObjectsOfClass:(NSString *)class
{

    for ([class class] *obj in arr)
    {

        // Do stuff

    }

}

So I might call this like

NSArray *arr = [NSArray arrayWithObjects:@"foo",@"bar", nil];
[self doStuffInLoopForDataArray:arr forObjectsOfClass:@"NSString"];

and I would expect the code to be executed as if I had wrote

- (void) doStuffInLoopForDataArrayOfStrings:(NSArray *)arr
{

    for (NSString *obj in arr)
    {

        // Do KVC stuff

    }

}

Is there a way to get this kind of behavior?

3

There are 3 answers

0
GeneralMike On BEST ANSWER

Another approach would be to create a single superclass that all the classes I'd like to use this method for inherit from. I can then loop using that superclass.

So if I want to be able to loop for MyObject1 and MyObject2, I could create a BigSuperClass, where MyObject1 and MyObject2 are both subclasses of BigSuperClass.

- (void) doStuffInLoopForDataArray:(NSArray *)arr
{

    for (BigSuperClass *obj in arr)
    {

        // Do stuff

    }

}

This loop should work for arrays of MyObject1 objects, arrays of MyObject2 objects, or arrays of BigSuperClass objects.

The more I've been thinking about this, the more I'm leaning towards this being the best approach. Since I can setup my BigSuperClass with all the @propertys and methods I'd be interested in as part of my // Do Stuff, which means I won't have to check respondsToSelector as with the other answers. This way just doesn't feel quite as fragile.

0
GeneralMike On

I came up with an idea while I was typing up this question, figured I might as well finish it. I just need to change how I'm doing my loop, and I don't really need to send in the class.

- (void) doStuffInLoopForDataArray:(NSArray *)arr
{

    for (int i=0; i < [arr count]; i++)
    {

        // Do stuff

    }

}

I should note that part of my // Do stuff is checking to make sure if ([[arr objectAtIndex:i] respondsToSelector:...]) before I actually try to do anything with it - and from what I understand that should prevent any nasty crashes.

0
Wain On

I don't see much point in passing the class to the method. Run your loop as:

for (id obj in arr) {

and check the methods you want to call exist. Passing the class is only really useful if you want to check that the objects in the array are actually of that class, but you couldn't then do much with that information.