77

I have an NSArray and need to filter out any strings that are null or rather, have ' ' (empty string). How do I do that? I have tried doing:

NSPredicate *predicateName = [NSPredicate predicateWithFormat:@"(name!=nil)"]; 

but that doesn't seem to work. Or maybe it does but there are different kinds of null...

4 Answers 4

153

If you don't use Core Data, you could do:

NSPredicate *predicateName = [NSPredicate predicateWithFormat:@"name.length > 0"];

If the string is empty, this will fail (because 0 == 0). Similarly, if name is nil, it will also fail, because [nil length] == 0.

15
  • So then what is the solution mate? This one actually seems to work for me where as the first answer doesn't. If string is empty, then wont length = 0? it isn't null
    – Doz
    Sep 10, 2011 at 4:56
  • 87
    !!! Beware with CoreData length is not supported, and worse will fail silently returning strange results. CoreData translates the predicate name.length > 1 to sqlite in name > 1... While it should be length(name) > 1 May 7, 2012 at 14:06
  • 34
    Got tricked once again today by this one with CoreData... damn it. Kinda funny that I found my own previous comment looking for this :) Mar 14, 2013 at 12:38
  • 8
    @VincentG - then what is the solution for CoreData?
    – RyanJM
    Mar 5, 2014 at 21:44
  • 2
    This is very dangerous. @VincentG is right. I have a string with a leading '/' character which did not work with .length. I had to use the name!=nil AND name!='' like @josema.vitaminew posted
    – Stefan Arn
    Nov 20, 2015 at 13:09
88

I think this should work:

NSPredicate *predicateName = [NSPredicate predicateWithFormat:@"name!=nil AND name!=''"]; 
1
  • 3
    This works find for Realm database predicates as well. Thank you.
    – edhnb
    May 1, 2017 at 15:41
14
 NSPredicate *predicateName = [NSPredicate predicateWithFormat:@"name!=NULL"];
7

This predicate worked for me:

[NSPredicate predicateWithFormat:@"(%K== nil) OR %K.length == 0", @"imageUrl", @"imageUrl"]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.