3

I need to filter an array by a property from an object that is inside another array. Let's say that I got two classes like:

StoreList.h

@interface StoreList : NSObject {
  NSMutableArray *storesArray; //Array containing Store objects
}

Store.h

@interface Store : NSObject {
  NSString *name;
}

So, I have an NSArray (storeListArray) that have some StoreList objects in it. Then, my Array is something like this:

storeListArray = [
 StoreList:{
    storesArray: {
                  stores[{
                    store: {
                     name: "Store1"
                    },
                    store: {
                     name: "Store2"
                    }
                  }]
                },
    storesArray: {
                  stores[{
                    store: {
                     name: "Store1"
                    },
                    store: {
                     name: "Store2"
                    }
                  }]
                }
   }
];

Well, my question is: How can I filter storeListArray by the "name" property of the Store Object, using NSPredicate?

I was trying to do something like this, but this don't work:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY storeList CONTAINS[cd] %@", filterString];
self.filteredStores = [storeListArray filteredArrayUsingPredicate:predicate];
return self.filteredStores;

Thanks for helping!

FelipeDev.-
  • 3,113
  • 3
  • 22
  • 32

2 Answers2

2

Try this,

NSPredicate * predicate = [NSPredicate predicateWithFormat:@"ANY SELF.storesArray.name == %@", filterString];

NSArray * videoArray = [storeListArray filteredArrayUsingPredicate:predicate];
Khalil
  • 238
  • 2
  • 15
0

have you tried as like below,

NSPredicate * predicate = [NSPredicate predicateWithFormat:@"name == %@", filterString];

NSArray * videoArray = [storeListArray filteredArrayUsingPredicate:predicate];

Thanks!

Natarajan
  • 3,241
  • 3
  • 17
  • 34
  • 1
    Yes, that was the first thing that I did. But it gives me the error: * Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[StoreList valueForUndefinedKey:]: this class is not key value coding-compliant for the key name.' – FelipeDev.- Mar 20 '14 at 19:30
  • The above would work if storeListArray contained store objects, instead of arrays of store objects. Perhaps filter each child array in a loop? Or flatten storeListArray before filtering? – Joshua Kaden Mar 20 '14 at 19:51
  • @JoshuaKaden I tried doing a Loop, but can't return the filtered List. Can you please provide me some example using the flatten thing? – FelipeDev.- Mar 20 '14 at 20:03
  • Sure; just check out [http://stackoverflow.com/questions/17087380/flatten-an-nsarray]. – Joshua Kaden Mar 20 '14 at 20:20