2015-03-25 141 views
5

我想使用NSPredicate从下面显示的结构中筛选所有CustomObjects,并且对它们的属性“isSelected”具有值true。 我有一个嵌套结构,如:isSelectedProperty-Object-NSArray-NSDictionary-NSArrayNSPredicate基于它的属性从嵌套结构筛选自定义对象

[ 
    { 
    "title": "ABC", 
    "list": [ 
     <CustomObject>.isSelected = true, 
     <CustomObject>.isSelected = true, 
     <CustomObject>.isSelected = true 
    ] 
    }, 
    { 
    "title": "ABC", 
    "list": [ 
     <CustomObject>.isSelected = false, 
     <CustomObject>.isSelected = true, 
     <CustomObject>.isSelected = true 
    ] 
    }, 
    { 
    "title": "ABC", 
    "list": [ 
     <CustomObject>.isSelected = false, 
     <CustomObject>.isSelected = true, 
     <CustomObject>.isSelected = true 
    ] 
    } 
] 

从这样的嵌套结构我需要筛选具有isSelected = true所有CustomObject。所以我的问题是,

  • 是否有可能使用NSPredicate?
  • 是的,那么过滤这个结构的谓词语句是什么?

请提供一些理解,以便我们能够理解如何实际处理这样的结构。

编辑 - 非常接近解决方案

谷歌搜索和莫哈末·瓦卡斯的答案的帮助下,我在滤波阵列成功,因为下面使用

NSPredicate *aPredicate = [NSPredicate predicateWithFormat:@"list.isSelected CONTAINS[c] %@",@true]; 
NSArray *aArray = [mutArrContacts filteredArrayUsingPredicate:aPredicate]; 
NSArray *UnWrapped = [aArray valueForKey:@"list"]; 



<__NSArrayI 0x7fc969cde360>(
<__NSArrayM 0x7fc969f54a10>(
<ContactData: 0x7fc969f7a590>, 
<ContactData: 0x7fc969f8dee0> 
) 
, 
<__NSArrayM 0x7fc969f736f0>(
<ContactData: 0x7fc969f68310> 
) 
, 
<__NSArrayM 0x7fc969f737a0>(
<ContactData: 0x7fc969f70340> 
) 
, 
<__NSArrayM 0x7fc969f87430>(
<ContactData: 0x7fc969f65170> 
) 
, 
<__NSArrayM 0x7fc969f874d0>(
<ContactData: 0x7fc969f51690> 
) 

) 

,但现在我很努力过滤此对象成单个数组像

(
<ContactData: 0x7fc969f7a590>, 
<ContactData: 0x7fc969f8dee0>, 
<ContactData: 0x7fc969f68310>, 
<ContactData: 0x7fc969f70340>, 
<ContactData: 0x7fc969f65170>, 
<ContactData: 0x7fc969f51690> 
) 

回答

5

是的,你可以使用NSPredicate像这样过滤自定义对象

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY list.isSelected = %@",@true]; 
NSArray *filteredArry=[[json filteredArrayUsingPredicate:predicate] copy]; 

希望这会帮助你。

+0

这是崩溃。 '由于未捕获的异常'NSUnknownKeyException',原因:'[ valueForUndefinedKey:]终止应用程序:此类不是关键值编码兼容的关键字ContactData。' ' 这里ContactData是NSObject的子类,已经在MyQuestion中作为CustomObject进行了修改。 – Mrug 2015-03-25 08:10:27

+0

我已经编辑我的答案,请检查它 – 2015-03-25 09:35:26

+0

使用NSPredicate * aPredicate = [NSPredicate predicateWithFormat:@“list.isSelected CONTAINS [c]%@”,@ true];'我能够获得过滤数组,但它的多维,但我试图让它在单个数组中。明白我的观点? – Mrug 2015-03-25 09:52:42