Search code examples
iosnsmutablearraynsarraynsindexset

removeObjectsAtIndexes causing a crash


Can't figure out whats causing the crash here. Im enumerating over a NSMutableArray and placing the indexes of certain objects into a mutable index set, then attempting to remove the corresponding objects from the array. here is my code

  NSMutableIndexSet *itemsToRemove;

UIBarButtonItem *item;
NSUInteger index;

for (item in self.rightView.toolbarItems)
{
    if (item.tag == MLPAD_RIGHT_VC_BACK_TO_CENTRAL_ITEM_TAG){
        [itemsToRemove addIndex:index];
        index ++;
    }
}

[self.rightView.toolbarItems removeObjectsAtIndexes:itemsToRemove];

the last line is crashing and giving me an EX_BAD_ACCESS.

any ideas why? thanks


Solution

  • You're not allocating/initializing itemsToRemove - if you're using ARC, it's initialized to nil, if not, it potentially contains garbage - neither one is acceptable if you want it to be passed as an argument later...

    Neither do you initialize index to zero...

    (Why am I suspecting that you're coming from a managed language?...)

    Unrelated to the crash, but it's still a semantic error: you have to increment index even if the conition is not met:

    for (item in self.rightView.toolbarItems)
    {
        if (item.tag == MLPAD_RIGHT_VC_BACK_TO_CENTRAL_ITEM_TAG) {
            [itemsToRemove addIndex:index];
        }
        index ++;
    }