Search code examples
objective-cnullnsnull

Objective C NSPredicate predicateWithBlock removing nil/null values


I am trying to populate an array by taking an existing array and removing nil values from it. The array was populated from a the JSON response of an http call. Sometimes the array has a null value at the end, and the easiest way to remove that value so I wouldn't have to handle it everywhere in my code would be to use NSArray's filteredArrayUsingPredicate: to assign the variable into the instance variable I use throughout my class.

NSArray *respAgencyList = (NSArray*) [JSON valueForKeyPath:@"xml.path.to.data" ];
NSLog(@"data before filter: %@", respAgencyList); 
// prints: ( { domain: "foo.com", name:"foobar"}, "<null>" });
if (respAgencyList != nil && respAgencyList.count > 0) {
    agencies = [respAgencyList filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
            NSLog(@"Evaluated object is %@", evaluatedObject); //prints <null> for the null value
            BOOL ret = evaluatedObject != nil;
            return ret;

        }]];
}

In the above code the return value is always YES. However, when I put the debugger on and step through it I see:

evaluatedObject = id 0x00000000

enter image description here

Isn't this a null/nil value? What is different about this value compared to nil?


Solution

  • You should also check for NSNull, which can be placed into an NSArray since it is a proper object.

    BOOL ret = (evaluatedObject != nil && [evaluatedObject isKindOfClass:[NSNull class]] == NO);