NSPredicate to test for NULL, and blank strings

IosObjective CNspredicate

Ios Problem Overview


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

Ios Solutions


Solution 1 - Ios

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.

Solution 2 - Ios

I think this should work:

NSPredicate *predicateName = [NSPredicate predicateWithFormat:@"name!=nil AND name!=''"]; 

Solution 3 - Ios

 NSPredicate *predicateName = [NSPredicate predicateWithFormat:@"name!=NULL"];

Solution 4 - Ios

This predicate worked for me:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDozView Question on Stackoverflow
Solution 1 - IosDave DeLongView Answer on Stackoverflow
Solution 2 - IosJosé Manuel SánchezView Answer on Stackoverflow
Solution 3 - IoschrowwView Answer on Stackoverflow
Solution 4 - IosJosip B.View Answer on Stackoverflow