2011-09-10 125 views
64

我有一個NSArray,並需要過濾掉任何字符串爲空或相反,有''(空字符串)。我怎麼做?我曾嘗試過:NSPredicate測試NULL,並空白字符串

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

但這似乎並不奏效。或者,也許它,但也有不同種類的空的...

回答

130

如果你不使用的核心數據,你可以這樣做:

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

如果字符串是空的,這將失敗(因爲0 == 0 )。同樣,如果namenil,它也會失敗,因爲[nil length] == 0

+0

,那麼什麼是解決伴侶嗎?這個實際上似乎適用於我,因爲第一個答案沒有。如果字符串是空的,那麼將不會長度= 0?它不是null – Doz

+0

@Doron解決方案是使用我建議的謂詞。 –

+0

對不起,但我仍然在某些領域得到(null)。因此,在代碼之後不確定您的評論意味着什麼。 == 0所以你說你得到的值爲0,所以我需要測試是> 0.爲1.因爲我仍然越來越(空) – Doz

63

我認爲這應該工作:

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

這對我的情況很奏效。謝謝。 – Isuru

+2

這也適用於Realm數據庫謂詞。謝謝。 – mtb

5

該斷言爲我工作:

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