【问题标题】:How to Filter an NSMutableArray of Dictionaries?如何过滤字典的 NSMutableArray?
【发布时间】:2012-11-02 13:16:50
【问题描述】:

我有一个由联系人字典组成的可变数组

[
{
"name":""
"Email":""
type:"A"
},
"name":""
"Email":""
type:"B"
}
"name":""
"Email":""
type:"C"
}........100 contacts
]

我想通过分段开关处理的 A、B 或 C 类型来过滤它们。我的问题是如何使用谓词来过滤这种类型的情况。

这是我的过滤实现

-(NSArray *)filtercontcts:(NSString *)filterParameter
{
    NSArray *filterContacts = [[NSArray alloc]init];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"type ==  %@)",filterParameter];

    filterContacts= [contacts filteredArrayUsingPredicate:predicate];

    return filterContacts;

}

非常感谢您的帮助。

【问题讨论】:

    标签: ios dictionary nsmutablearray nsdictionary


    【解决方案1】:

    创建谓词的正确方法是不带右括号,如下所示:

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"type ==  %@", filterParameter];
    

    您也泄漏了内存,因为您分配了filterContacts,但是当您用filteredArrayUsingPredicate: 覆盖指针时丢失了对它的引用,只需删除[[NSArray alloc]init]; 即可消除泄漏。

    【讨论】:

    • arc 不照顾??
    • @DheerajKaveti,在 ARC 中,你可以写 NSArray *filterContacts; 其他部分不需要。它类似于非弧形中的NSArray *filterContacts = [[NSArray alloc]init]; [filterContacts release]; filterContacts= [contacts filteredArrayUsingPredicate:predicate];,它可能不会泄漏任何东西,但显然不需要。
    • 当你想要更多他们到每个字典中的键时,你如何过滤?让我们说类型和名称以及字典有 10 个键值的位置
    【解决方案2】:

    试试这样:-

    NSArray *filterContacts = [[NSArray alloc]init];
    NSPredicate *predicate=[NSPredicate predicateWithFormat:@"category type[cd] %@,filterParameter];
    filterContacts=[contacts filteredArrayUsingPredicate:predicate]mutableCopy]; 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多