首页 > 移动平台 > 详细

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

时间:2015-08-06 15:04:06      阅读:596      评论:0      收藏:0      [点我收藏+]

使用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"];
}




版权声明:本文为博主原创文章,未经博主允许不得转载。

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

原文:http://blog.csdn.net/lvxiangan/article/details/47316325

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!