ios NSPredicate 测试 NULL 和空白字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7369390/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 21:26:52  来源:igfitidea点击:

NSPredicate to test for NULL, and blank strings

iosobjective-cnspredicate

提问by Doz

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

我有一个NSArray并且需要过滤掉任何为空的字符串,或者更确切地说,有 ' ' (空字符串)。我怎么做?我试过这样做:

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

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

但这似乎不起作用。或者也许确实如此,但是有不同种类的空...

回答by Dave DeLong

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

如果你不使用 Core Data,你可以这样做:

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

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

如果字符串为空,这将失败(因为0 == 0)。同样,如果namenil,它也会失败,因为[nil length] == 0

回答by José Manuel Sánchez

I think this should work:

我认为这应该有效:

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

回答by chroww

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

回答by Josip B.

This predicate worked for me:

这个谓词对我有用:

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