测试 NULL 和空字符串

我有一个 NSArray,需要过滤掉任何为空的字符串,或者说,有’(空字符串)。我该怎么做?我试过这么做:

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

但这似乎不起作用。或者也许起作用了,但是有不同种类的无效..。

61306 次浏览

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.

I think this should work:

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

This predicate worked for me:

[NSPredicate predicateWithFormat:@"(%K== nil) OR %K.length == 0", @"imageUrl", @"imageUrl"]
 NSPredicate *predicateName = [NSPredicate predicateWithFormat:@"name!=NULL"];