Search code examples
iosobjective-ckvc

Looping through an array of dynamic objects


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?


Solution

  • 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.