I have an object that act on UserDefaults.
It adds things into an Array into userdefaults, then removes it when some events occurs.
That object can have more than one instance.
Those calls coming from different objects instance seems to collide and generate a crash :
*** Terminating app due to uncaught exception 'NSGenericException', reason: '*** Collection <__NSCFArray: 0x66061e0> was mutated while being enumerated.<CFArray 0x66061e0 [0xe38400]>{type = mutable-small, count = 3, values = (
I remove my items like this :
// ==========================================================================================================
- (void) deleteSavedItem:(NSString*)keycodeToDelete
// ==========================================================================================================
{
NSMutableArray* savedItems = [[self loadAllSavedItems] mutableCopy];
for (NSDictionary* dict in savedItems) {
NSString* keycode = [dict objectForKey:@"keycode"];
if ([keycode isEqualToString:keycodeToDelete])
[savedItems removeObject:dict];
}
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
[defaults setValue:savedItems forKey:@"savedItems"];
[defaults synchronize];
[savedItems release];
}
// ==========================================================================================================
- (NSArray*) loadAllSavedItems
// ==========================================================================================================
{
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
NSArray* savedItems = [defaults arrayForKey:@"savedItems"];
if (savedItems == nil) savedItems = [NSArray array];
return savedItems;
}
How may I add/remove things from that array without collision ?
I’m not sure the reason is the many objects that use default that causes this crash. I suspect too that this is the way I parse the array.
I need to keep my objects instances, and keep them running process parralel.
You must never alter an array while fast enumerating it. It will raise an exception as it did for you. You can get the items that satisfy your condition using
and then remove them using,
Modified
deleteSavedItem:would be.