Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing an object from a mutable dictionary throws an exception

I'm getting an exception after attempting to remove an object from a NSMutableDictionary. The relevant code follows. The 'settings' is passed to the method and can be a NSDictionary or a NSMutableDictionary.

 NSMutableDictionary *mutableSettings = nil;
 if ([settings isKindOfClass:[NSMutableDictionary class]])
     mutableSettings = (NSMutableDictionary *)settings;
 else 
     mutableSettings = [[[NSMutableDictionary alloc] initWithDictionary:settings] autorelease];

 [mutableSettings removeObjectForKey:@"akey"];

This crashes with

* Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[__NSCFDictionary removeObjectForKey:]: mutating method sent to immutable object'

Whats wrong with this? Thanks.

like image 872
pmf Avatar asked Apr 21 '12 16:04

pmf


1 Answers

The problem here is that both NSDictionary and NSMutableDictionary return __NSCFDictionary as their class, due to the fact that NSDictionary is a class cluster.

I think you will just have to make a mutable copy of the settings dictionary whether it is mutable or not.

NSMutableDictionary *mutableSettings = [settings mutableCopy];
like image 118
mttrb Avatar answered Nov 06 '22 19:11

mttrb