Paresh Masani
Paresh Masani

Reputation: 7504

iOS: FilterUsingPredicate on custom objects

I have a custom class extending NSObject. I am maintaining NSMutableArray of this class objects. Here is the situation,

customObject-class {
   NSString *name;
   int ID;
   .....and many other properties;
}

customObjectsArray [
   customObject1,
   customObject2,
   ...etc
]

Now I am trying to use filterUsingPredicate to remove objects that has nil names, like below but it returns very few or none objects while I know that there are hundreds of objects that has name not nil or empty. Could someone please tell me what could be wrong here.

[customObjectsArray filterUsingPredicate:[NSPredicate predicateWithFormat:@"name != nil"]];

Upvotes: 1

Views: 3317

Answers (2)

Paresh Masani
Paresh Masani

Reputation: 7504

As I replied to @rdelmar, I found an issue. This predicate was getting called before customObject1's data were actually initialised. I should check the status of data flag that says data has been initialised for this particular object and then apply filter. It worked. If data is not initialised all object's name is off course nil!

Upvotes: 0

Bogdan Andresyuk
Bogdan Andresyuk

Reputation: 523

Why won't you try like this:

NSMutableArray *array=...;
[array filterUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
    CustomObject *customObject=(CustomObject *) evaluatedObject;
    return (customObject.name!=nil);
}]];

Upvotes: 5

Related Questions