我有幾個有關NSPredicates的問題,這裏是他們;編寫一個NSPredicate
1.)我的代碼如下;
NSArray *arr= [self.humanArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"ANY name IN %@ ", nameArray]];
我得到以下異常;
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'The left hand side for an ALL or ANY operator must be either an NSArray or an NSSet.'
*** Call stack at first throw:
當我寫謂詞爲@"name IN %@ ", nameArray
。它有效,但我認爲這可能有一些缺陷。
注意:humanArray
包含HUMAN
的對象,而human
的對象包含以下屬性。 name
,age
,gender
,country
,region
。
2.)我想我在這裏做什麼是錯誤的。用戶可以選擇過濾self.humanArray
。用戶可以使用以下標準中的一項或多項進行篩選;
name, age, gender, country or region.
我的代碼看起來像這樣;
NSArray *fRegionArray= [self.humanArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"regionIN %@ ", regionArray]];
NSArray *fCountryArray= [fRegionArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"country IN %@ ", countryArray]];
NSArray *fNameArray= [fCountryArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"name IN %@ ", nameArray]];
此代碼的工作,如果用戶選擇的所有過濾器的屬性(region
,country
和name
)。如果你看上面的代碼,你會注意到第一個謂詞的輸出數組用於第二個謂詞中的過濾。所以這就是它以這種方式行事的原因。
我需要修改上面的代碼,以便用戶可以輸入任何屬性進行過濾。 region
或country
或name
。
對於問題1)所以我不能在上面的謂詞中使用任何與IN? 問題2)你能告訴我一個例子怎麼做嗎? – Illep 2012-02-08 16:31:15
for 1)只是略過ANY,並不意味着要這樣使用 2)只需創建一個可變數組,然後從每個謂詞的結果中添加對象,然後removeDuplicates – 2012-03-15 13:14:22