Search code examples
objective-ctypesprotocolsfor-in-loop

Objective C - Loop through NSArray where all objects inherit from same protocol


I have an NSArray where all objects inherit methods from the same protocol. What I want to do is something like:

NSArray* arr =  [NSArray arrayWithObjects:[Type_1 init],[Type_2 init], nil];

for(Protocol *element in arr)
{
  [element do_this];
}

arr is the array with the objects Type_1 and Type_2 which both inherit from the protocol named Protocol.

The problem is that Protocol can't be used as a type in the for in loop. How do I solve this?


Solution

  • Use:

    for(id < Protocol > element in arr)
    

    to specify that the objects are of a generic type and which implement the protocol.

    Alternatively, you could 'cheat' a little and use:

    [arr makeObjectsPerformSelector:@selector(do_this)];
    

    (doesn't provide any kind of checks).