使用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'
时间: 2024-10-15 17:56:15