您的位置:首页 > 移动开发 > IOS开发

iOS之NSMutableDictionary导致程序崩溃:'NSInternalInconsistencyException'

2015-08-06 14:39 369 查看
使用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"];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: