-3

NSArray在下面的示例中,我NSDictionaries需要从字典中提取 2 个值或删除不需要的值,我需要删除 id 和 NumberValue。你们中的任何人都知道我该怎么做吗?

Array: (
        {
            customerUS= {
                DisplayName = "level";
                InternalName = "Number 2";
                NumberValue = 1;
                id = xwrf
            },
            customerCAN= {
                DisplayName = "PurchaseAmount";
                InternalName = "Number 1";
                NumberValue = 3500;
                id = adf;
            };
        }
      )

我会非常感谢你的帮助。

4

4 回答 4

2

首先,您不能删除/插入/更新(immutable) NSDictionary/NSArray中需要转换NSDictionary/NSArray(mutable) 的值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 loopand removeObjectForKey,如果您有字典数组并且两者都是可变的,那么您还可以从数组的所有元素中删除一个键及其对象,如下所示:

[newMutableArr makeObjectsPerformSelector:@selector(removeObjectForKey:) withObject:@"id"];
[newMutableArr makeObjectsPerformSelector:@selector(removeObjectForKey:) withObject:@"NumberValue"];
于 2013-09-05T04:41:29.573 回答
1

我建议您阅读 Apple 文档。

要在创建后修改任何 Collection 对象,您需要可变版本。因为NSDictionary我们有NSMutableDictionary. 在这里阅读。

我们有一个移除对象的方法:

- (void)removeObjectForKey:(id)aKey

还有其他方法。您可以在上述文档中轻松引用它们。

于 2013-09-05T04:38:43.660 回答
0

Find out removeObjectForKey for deleting record from NSMutabledictionary.

removeObjectForKey pass the key value whatever you have like

all this are your key DisplayName, InternalName, NumberValue, id

do like this

removeObjectForKey:@"id";
于 2013-09-05T04:44:40.097 回答
0

首先,您必须将数组转换为可变数组,然后您可以从字典中删除键值对。

NSMutableArray *mutableArray = [yourArray mutableCopy]; 
for(int i=0;i<mutableArray.count;i++){
  NSMutableDictionary *outerDictionary = [mutableArray objectAtIndex:i];
  for(NSString *key in outerDictionary.allKeys){
    NSMutableDictionary *innerDictionary = [outerDictionary objectForKey:key];
    [innerDictionary removeObjectForKey:@"id"];
    [innerDictionary removeObjectForKey:@"NumberValue"];
  } }
于 2013-09-05T05:32:50.750 回答