Question

Can I write code like the following? It seems to work, but I want to make sure that it is allowed/safe:

// menu is a NSMenu*
for (NSMenuItem *item in [menu itemArray]) {
    if (some condition) {
        [menu removeItem:item];
    }
}
Was it helpful?

Solution

If it doesn't immediately throw an exception (as modifying an array directly when enumerating it does) then it's probably okay. NSMenu may be giving you a copy of its internal array (assuming it's keeping its items in an NSArray).

For guaranteed safety, however, you might like to do this in two steps. Create another array to hold the items for removal, then enumerate that and do the removal:

NSMutableArray * itemsToRemove = [NSMutableArray array];
for( NSMenuItem *item in [menu itemArray] ){
    if( some condition ){
        [itemsToRemove addObject:item];
    }
}

for( NSMenuItem * item in itemsToRemove ){
    [menu removeItem:item];
}

OTHER TIPS

Just for the record:
if you care about memory and dont want to create a secondary array use this:

for (int i = menu.itemArray.count - 1; i >= 0; --i)
{
    if( some condition for index i ){
        [menu removeItemAtIndex:i];
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top