iOS之NSMutableDictionary导致程序崩溃:'NSInternalInconsistencyException'
2015-08-06 14:39
369 查看
使用NSMutableDictionary时,如果操作不当,有可能会引起程序崩溃。示例代码:
执行上述代码后报错:
出错原因在于:
[NSJSONSerialization
JSONObjectWithData:data options:NSJSONReadingMutableLeaves
error:nil];
返回的结果是immutable对象,不能直接对immutable进行赋值操作,否则会报错。
修改后代码:
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 ViewController 页面跳转
- IOS开发 工具片篇
- iOS ——版本更新检测 判断应用版本和升级提示
- [转] iOS 开发:绘制像素到屏幕
- iOS风格的Titlebar
- iOS用户点击事件处理
- 查看iOS真机日志
- iOS设计模式之中介者模式
- iOS_导航栏的navigationBar.hidden与navigationBarHidden的区别
- iOS开发之-自定义设置字体
- iOS The identity used to sign the executable is no longer valid
- ios开发之---将数据写入和读取与沙盒的具体理解和实现。
- ios 快捷键使用
- iOS绘图API的使用
- iOS 8.4越狱(iPhone6)
- ios code test
- iosTest
- iOS imageName方法获取Folder文件夹(蓝色文件夹)内图片
- iOS开发无第三方控件的援助达到的效果侧边栏
- ios各种动画效果