【问题标题】:Editting NSMutableDictionary in array在数组中编辑 NSMutableDictionary
【发布时间】:2011-08-12 20:26:00
【问题描述】:

我有一个问题:我有一个 NSMutableArray,我在多个视图中传递它。在其中一个视图中,可以编辑该数组 (NSMutableDictionary) 内的对象的值。我使用代码做到这一点:

NSMutableDictionary *tester = [[NSMutableDictionary alloc] initWithDictionary:selectedItem copyItems:YES];
NSMutableString *newLoc = [[NSMutableString alloc] initWithString:locationField.text]; 
[tester setValue:newLoc forKey:@"Location"];
[selectedList replaceObjectAtIndex:[selectedList indexOfObject:selectedItem] withObject:tester];

我遇到的问题是替换 selectedList 中的那个对象。它给出了错误*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayI replaceObjectAtIndex:withObject:]: unrecognized selector sent to instance 0xa631e30' 如果我将新项目复制到 selectedList 的复制数组中,然后再次使用新值分配 selectedList,则它可以工作,但是其他视图在数组中再次找到相同的列表(新分配的位置)时遇到问题。

TL;DR 版本:如何在 NSMutableArray 中编辑值(通过替换?)?为什么 replaceObjectAtIndex 不起作用?

编辑:它确实是不可变的。尽管如此,主要问题仍然存在: 我有:

NSMutableDictionary *tester = [[NSMutableDictionary alloc] initWithDictionary:geselecteerdItem copyItems:YES];
[geselecteerdItem setValue:nieuweLoc forKey:@"Location"];
[geselecteerdeLijst replaceObjectAtIndex:[geselecteerdeLijst indexOfObject:tester] withObject:geselecteerdItem];

当我使用:[warningList replaceObjectAtIndex:[warningList indexOfObject:geselecteerdeLijst] withObject:keuzeLijst] 时,它给了我一个 outofbounds 错误,因为数组 geselecteerdeLijst 的索引在warningList 中明显改变了。有什么想法吗?

【问题讨论】:

  • 是您的字典中的 selectedItem,如果是,那么您的数组 selectedList 是否包含字典。请详细说明你的数据结构。你可以放 nslog 看看值是否正确。

标签: iphone objective-c arrays xcode dictionary


【解决方案1】:

selectedList 是一个不可变 数组,不支持任何修改。不过,您可以这样做:

NSMutableArray *tmp = [NSMutableArray arrayWithArray: selectedList];
[tmp replaceObjectAtIndex:[selectedList indexOfObject:selectedItem] withObject:tester];

编辑:澄清一下,__NSArrayINSArray 的具体不可变子类,__NSArrayM 是可变子类。您不应该依赖私有类名,但由于它们自己说话,您至少可以知道哪些是可变的,哪些不是。

【讨论】:

  • @Joetjah 确保在发送[geselecteerdeLijst indexOfObject:tester] 之前将tester 添加到geselecteerdeLijst,否则会返回NSNotFound,这肯定是越界了。
  • 您好,这是正确的,但错误发生在其他地方。因为我在 geselecteerdeLijst 中编辑了一个项目,所以它以某种方式编辑了 geselecteerdeLijst 所在的数组。它更改了 geselecteerdeLijst 的索引,而我只替换了 geselecteerdeLijst 中的一个对象。
猜你喜欢
  • 2011-02-24
  • 1970-01-01
  • 2015-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-09
相关资源
最近更新 更多