使用NSMutableDictionary时,如果操作不当,有可能会引起程序崩溃。示例代码:
NSString *result = @"{\"username\”:\”aaa\”,\"phone\":\"15666666666\",\"bankcount\":\"98765432112345678\"}";
NSData *data = [result dataUsingEncoding:NSUTF8StringEncoding];
NSMutableDictionary *info = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
if (info) {
NSString *username = [Utils UrlDecode: info[@"username"]];
[info setObject:username forKey:@"username"];
}
执行上述代码后报错:
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[__NSCFDictionary setObject:forKey:]: mutating method sent to immutable object'
出错原因在于:
[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
返回的结果是immutable对象,不能直接对immutable进行赋值操作,否则会报错。
修改后代码:
NSString *result = @"{\"username\”:\”aaa\”,\"phone\":\"15666666666\",\"bankcount\":\"98765432112345678\"}";
NSData *data = [result dataUsingEncoding:NSUTF8StringEncoding];
//----将immutable转换为mutable----
NSMutableDictionary *temp = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
NSMutableDictionary *info = [NSMutableDictionary dictionaryWithDictionary:temp];
//----------------------
if (info) {
NSString *username = [Utils UrlDecode:info[@"username"]];
[info setObject:username forKey:@"username"];
}
NSMutableDictionary *dic = [getDefaults valueForKey:@"loginInfo"];
[dic2 setObject:tf1.text forKey:@"phone"];
报错:
'-[__NSCFDictionary setObject:forKey:]: mutating method sent to immutable object
修改:
NSMutableDictionary *dic = (NSMutableDictionary *)[getDefaults valueForKey:@"loginInfo"];
NSMutableDictionary *dic2 = [NSMutableDictionary dictionaryWithDictionary:dic];
[dic2 setObject:tf1.text forKey:@"phone"];