我有NSDictionaries
的NSArray
,我需要从字典中提取2个值或删除不需要的值。在下面的示例中,我需要删除id和NumberValue。你们中有人知道我该怎么做吗?
Array: (
{
customerUS= {
DisplayName = "level";
InternalName = "Number 2";
NumberValue = 1;
id = xwrf
},
customerCAN= {
DisplayName = "PurchaseAmount";
InternalName = "Number 1";
NumberValue = 3500;
id = adf;
};
}
)
我真的很感激你的帮助。
首先,您不能移除/插入/更新中的值(不可变)NSDictionary/NSArray
,您需要将NSDictionary/NSArray
转换为(可变)NSMutableDictionary/NSMutableArray
。
比如
NSArray *myArr = ....;
NSMutableArray *newMutableArr = [myArr mutableCopy];
然后您可以在newMutableArr中进行更改。
像
for(int i = 0 ; i < newMutableArr.count ; i ++)
{
[[newMutableArr objectAtIndex:i] removeObjectForKey:@"id"];
[[newMutableArr objectAtIndex:i] removeObjectForKey:@"NumberValue"];
}
编辑:
在不使用for loop
和removeObjectForKey
的情况下,如果您有dictionary数组,并且这两个数组都是可变的,那么您也可以从数组的所有元素中删除键及其对象,如下所示:
[newMutableArr makeObjectsPerformSelector:@selector(removeObjectForKey:) withObject:@"id"];
[newMutableArr makeObjectsPerformSelector:@selector(removeObjectForKey:) withObject:@"NumberValue"];
我建议您阅读Apple文档。
要在创建任何Collection对象后对其进行修改,您需要可变版本。对于NSDictionary
,我们有NSMutableDictionary
。请阅读此处。
我们有一种去除物体的方法:
- (void)removeObjectForKey:(id)aKey
还有其他方法。您可以在上面提到的文档中轻松地参考它们。
查找removeObjectForKey以从NSMutabledictionary中删除记录。
removeObjectForKey像一样传递键值
所有这些都是你的钥匙DisplayName,InternalName,数字值,id
喜欢这个吗
removeObjectForKey:@"id";
首先必须将数组转换为可变数组,然后才能从字典中删除键值对。
NSMutableArray*mutableArray=[yourArray mutableCopy]
for(int i=0;i<mutableArray.count;i++){
nbsp;NSMutableDictionary*outerDictionary=[mutableArray objectAtIndex:i];
for(outerDicionary.allKeys中的NSString*key){
nbsp; NSMugableDictionary*innerDictionary=[outerDiction objectForKey:key];
nbsp;&nnbsp;[ninnerDiction removeObjectForKey:@"id"];
;[ninnerDictionary removeObjectForKey:@"NumberValue"]
}}