我正在尝试使用 NSPredicate 从如下所示的结构中过滤所有 CustomObjects,并为其属性“isSelected”设置值为 true。
我有一个嵌套结构,如:isSelectedProperty-Object-NSArray-NSDictionary-NSArray
。
[
{
"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?
- 是,那么过滤这个结构的谓词语句是什么?
请提供一些理解,以便我们了解如何实际处理此类结构。
编辑 - 非常接近解决方案
在 Muhammad Waqas 的回答帮助下进行谷歌搜索后,我成功地使用以下方法过滤了数组
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>
)
最佳答案
是的,你可以像这样使用 NSPredicate 过滤自定义对象
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY list.isSelected = %@",@true];
NSArray *filteredArry=[[json filteredArrayUsingPredicate:predicate] copy];
希望对您有所帮助。
关于ios - NSPredicate 根据嵌套结构中的属性过滤自定义对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29249667/