5
votes

I am trying to use NSPredicate to filter all CustomObjects from structure shown below, and having value true for their property "isSelected". I have an Nested structure like : 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
    ]
  }
]

From such Nested structure I need to filter all CustomObject having isSelected = true . So My Questions are,

  • Is it possible using NSPredicate?
  • Is Yes, then what will the predicate statement to filter this structure ?

Please provide some understanding so that we can understand how to actually deal with such structures.

EDIT - Very Near to Solution

After googling and help of answer of Muhammad Waqas, I succeed in filtering Array as below using

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>
)

)

But Now I am struggling to filter this Objects into Single array like

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

1 Answers

5
votes

YES you can filter custom objects using NSPredicate like this

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

hope this will help you.