Ethan Allen
Ethan Allen

Reputation: 14835

Why am I getting a NSFastEnumerationMutationHandler with this NSMutableArray code?

Can someone help me understand what I am doing wrong here that would caused this stack trace:

1   libobjc.A.dylib                 0x3a8a897a objc_exception_throw + 26
2   CoreFoundation                  0x32b7fd80 __NSFastEnumerationMutationHandler + 124
3   CoreFoundation                  0x32adbcee -[NSArray containsObject:] + 134

Here is the code:

NSMutableArray *leftoverArray = [[NSMutableArray alloc] initWithArray:itemsArray];
for (NSDictionary *tempItem in tempItemsArray)
{
      if (![itemsArray containsObject:tempItem])
      {
           [itemsArray addObject:tempItem];
      }
      else
      {
           [leftoverArray removeObject:tempItem];
      }
}
for (NSDictionary *item in leftoverArray)
{
      [itemsArray removeObject:item];
}
[mainController.tblView reloadData];

tempItemsArray is passed in to this class via:

@property (nonatomic, strong) NSMutableArray *tempItemsArray;

I do have this code elsewhere in my app:

if (appDelegate.loading)
    appDelegate.tempItemsArray = itemsArray;
else
    appDelegate.itemsArray = itemsArray;
[tblView reloadData];

Thanks!

Upvotes: 0

Views: 1253

Answers (1)

Valent Richie
Valent Richie

Reputation: 5226

Currently tempItemsArray and itemsArray are a reference to the same array object. You are technically looping and modifying the same array at the same time.

Try to make a copy of the array for the tempItemsArray or itemsArray:

if (appDelegate.loading)
    appDelegate.tempItemsArray = [NSMutableArray arrayWithArray:itemsArray];
else
    appDelegate.itemsArray = itemsArray;
[tblView reloadData];

Upvotes: 2

Related Questions