码迷,mamicode.com
首页 > 移动开发 > 详细

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

时间:2015-08-06 15:05:14      阅读:1137      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!