Monday, December 8, 2003

Cocoa Enumeration

Jonathan Rentzsch is back with a post about the macros he uses to tame Cocoa’s enumeration idiom. Here’s the macro I’ve been using:

#define foreach(object, enumerator) 
    id mjtForeachEnumerator ## object = (enumerator); 
    if ( [mjtForeachEnumerator ## object respondsToSelector:@selector(objectEnumerator)] ) 
        mjtForeachEnumerator ## object = [mjtForeachEnumerator ## object objectEnumerator]; 
    SEL mjtNextObjectSEL ## object = @selector(nextObject); 
    IMP mjtNextObjectIMP ## object = [mjtForeachEnumerator ## object methodForSelector:mjtNextObjectSEL ## object]; 
    id object; 
    while ( (mjtForeachEnumerator ## object) && 
            object = mjtNextObjectIMP ## object(mjtForeachEnumerator ## object, mjtNextObjectSEL ## object) )

3 Comments RSS · Twitter


A bit late, but some people might run into the same problem as I did. I tried your code but it would not compile, complaining about a wrong lvalue assignment. Turns out to be the assignment in the while statement. && has higher precedence then =, so the = will failt.

Solution:
surroung "object = mjtNextObjectIMP ## object(mjtForeachEnumerator ## object, mjtNextObjectSEL ## object)" with another pair of ()'s


Thinking about this some more, I think there's a bug in Rentzsch's macro because it evaluates OBJ more than once.


Here is an updated version of the macro that supports loop-scope variables and static typing.

Leave a Comment