0

我想在字典的数组中设置项目。我在下面有一个 NSDictionary,一个名为“currentCityNode”的实例。在该字典中是一个数组项(除其他外)。数组项名为“TheConnections” 下面的代码成功读取了数组。

 NSArray *theConnectionsArray = [currentCityNode objectForKey:@"TheConnections"];
 (theConnectionsArray now contains the previously loaded values '3','7', and '9')

现在我想在这个数组中设置一个值。将第二个值“7”设为“5”。

我已经尝试了一些变化,但还没有得到它。

[currentCityNode addObject:notsurewhattoputhere forKey:@"TheConnections"];
4

2 回答 2

1

你的数组和字典必须是可变的,这样的东西应该可以工作。如果 theConnectionsArray 已经是可变的,那么您不必使用mutableCopy.

NSMutableArray *theConnectionsArray = [[currentCityNode objectForKey:@"TheConnections"] mutableCopy];
[theConnectionsArray replaceObjectAtIndex:1 withObject:@"5"];
[currentCityNode setObject:theConnectionsArray forKey:@"TheConnections"];
于 2012-06-07T01:51:56.933 回答
1

如果您要检索的数组是可变的( 的实例NSMutableArray):

[[currentCityNode objectForKey:@"TheConnections"] addObject:@"objectToAdd"];

如果数组只是一个NSArray

NSArray *array = [currentCityNode objectForKey:@"TheConnections"];
NSMutableArray *mutableArray = [array mutableCopy];
[mutableArray addObject:@"objectToAdd"];
[currentCityNode setObject:[NSArray arrayWithArray:mutableArray] forKey:@"TheConnections"];
[mutableArray release];

本质上,如果数组是不可变的(因此不能轻易添加),您需要创建一个可变副本并将该副本分配回“TheConnections”。

于 2012-06-07T01:53:49.667 回答