ios - 替换数组中字典中的对象

标签 ios objective-c arrays nsarray nsdictionary

我的数组结构如下:

NSMutableArray topArray{
    NSMutableArray middleArray{
        NSMutableArray lowerArray{
            NSMutableDictionary dict{
            }
        }
    }
}

数组结构填充了我从网络检索的 JSON 格式的一些数据。

我正在尝试编辑 NSMutableDictionary 中的对象之一,如下所示:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSMutableArray *lowerArray = [[self middleArray] objectAtIndex:[indexPath section]];
    NSMutableDictionary *dict = [lowerArray objectAtIndex:[indexPath row]];

    [dict setObject:[NSNumber numberWithInt:1] forKey:@"key"];

    [[self tableView] reloadData];
}

每个数组中的数据都是正确的(我已经使用 print 语句进行了检查),但是,当我尝试更改字典中的对象时,出现以下错误: 原因:

'-[__NSCFDictionary setObject:forKey:]: mutating method sent to immutable object'

我需要在数组结构中更改字典中的对象。

这可能是 JSON 数据的问题吗,因为当 topArray 首次使用 JSON 数据初始化时,中间和较低的数组只是 NSArray 的形式?

抱歉,如果这令人困惑,如果您有任何疑问,我会尽力澄清更多信息。

预先感谢您的帮助。

最佳答案

如果您使用的是 NSJSONSerialization,则可以将 NSJSONReadingMutableContainers 传递给 +JSONObjectWithData:options:error 的 options 参数: ,并且所有解析的字典和数组都是可变的。

NSMutableArray *topArray = [NSJSONSerialization JSONObjectWithData:webServiceData 
                                                           options:NSJSONReadingMutableContainers 
                                                             error:nil];

关于ios - 替换数组中字典中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22797075/

相关文章:

ios - 从横幅/自定义操作启动应用程序时未调用 applicationDidBecomeActive

iphone - 如何将 NSObject 分配给 UILabel

php array_filter function not found or invalid function name 不管我输入什么

javascript - Internet Explorer 的数组 indexOf 实现

ios - 使用 AlamofireObjectMapper 将对象 json 数据映射到 2 个单独的数组中

ios - 更改从 xib 加载的 UITableViewHeaderFooterView 的背景颜色表示改用 contentView.backgroundColor

ios - 在 iOS 的 UIWebview 中添加 UIButton

iphone - 实时音频队列录音回放

objective-c - iOS UITableView numberOfRowsInSection 错误访问

php正则表达式读取带有选择字段的选择表单