Question

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

Was it helpful?

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 ++;
}

OTHER TIPS

Your primary problem is that itemsToRemove never gets initialized. You can't add an object to an NSMutableIndexSet that isn't really an NSMutableIndexSet - try setting itemsToRemove = [[NSMutableIndexSet alloc] init] or similar.

I also think where you have the statement index++ might be throwing some things off - if you only increment the index when you find an item you want to remove, you're effectively removing the first itemsToRemove.count items, instead of the actual items you want to get rid of. Think about incrementing the index unconditionally instead.

You have several issues. Not allocating itemsToRemove, not initilializing index (builtin stack variables are not auto-initialized) and not incrementing index on every loop iteration.

NSMutableIndexSet *itemsToRemove = [NSMutableIndexSet new];
NSUInteger index = 0;

for (UIBarButtonItem *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 index type of error can be minimized by using the block enumeration method, which passes in the current index.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top