2011-06-08 128 views
24

您好需要謂詞幫助。問題是我想要從數據庫獲取一個函數取決於它接收到的多個值,但這些值並不總是存在,這是否意味着我必須創建幾個不同的謂詞?具有多個參數的NSPredicate

下面

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"brand_id LIKE %@ AND brand_id LIKE %@ AND brand_id LIKE %@ AND brand_id LIKE %@ AND brand_id LIKE %@ AND item_category LIKE %@ AND item_make LIKE %@ AND item_gender LIKE %@ || item_price>%@ || item_price<%@", 
           brand_one, brand_two, brand_three, brand_four, brand_five, categoryString, makeString, genderString,[NSNumber numberWithInt:price_bottom],[NSNumber numberWithInt:price_top]]; 

brand_one,brand_two和等代碼有時存在,有時沒有。

它應該如何爲item_gender例如。如果沒有指定性別而不是擁有他們兩個,那就讓我們來看看。

對不起,如果我的問題描述混亂。在Gobras

基地評論下面的代碼是產生

NSArray *brands = [NSArray arrayWithObjects:brand_one, brand_two, brand_three, brand_four, brand_five, nil]; 

    NSPredicate *predicate_brands = [NSPredicate predicateWithFormat:@"brand_id like %@" argumentArray:brands]; 

什麼什麼搜索功能的合乎邏輯的解釋應該

  1. fetchrequest
  2. 謂詞獲取請求

謂語基於在5個品牌ID,物品ID,物品類別,物品製作,物品GE nder, 如果以上任何一項爲空,則應取出所有相關條目,例如,如果項目類別爲空,則應提取所有「珠寶,手錶等」,但應限制其餘謂詞表達式。

我是否應該爲品牌創建複合謂詞,然後爲值爲「item_category like Jewellery」和「item_category like Watches」的項目類別創建另一個項目類別,之後我該如何將它們合併到一起?

回答

62

組裝個別謂詞的適當收集到NSCompoundPredicate

NSMutableArray *parr = [NSMutableArray array]; 
if([brand_one length]) { 
    [parr addObject:[NSPredicate predicateWithFormat:@"brand_id LIKE %@",myBrandId]]; 
} 
if([brand_two length]) { 
    // etc 
} 

NSPredicate *compoundpred = [NSCompoundPredicate andPredicateWithSubpredicates:parr]; 

您最多可以疊加謂詞與orPredicateWithSubpredicates:andPredicateWithSubpredicates:和NSCompoundPredicate是一個NSPredicate自身可以合成。

https://developer.apple.com/documentation/foundation/nscompoundpredicate

+2

+1這是要走的路。 – TechZen 2011-06-08 14:45:04

+0

thanx沃倫,我仍然無法理解我的頭腦,我認爲這只是我的理解水平。我運行了很少的測試,似乎我現在有邏輯問題了......如果你能幫助我,我會非常感激......我已經添加了我想要做的邏輯解釋... – 2011-06-08 17:18:20

+0

以及我如何實際使用複合謂詞? cpred的價值在哪裏使用,它是在[NSPredicate predicateWithFormat]? – 2011-06-08 17:39:26

1

動態構建謂詞非常簡單:將謂詞格式字符串與所需的條件數組合起來,並使用參數構建相應的NSMutableArray[NSPredicate predicateWithFormat:argumentArray:]將完成其餘的工作。

+0

Thanx我試過這個,但它沒有抓取正確的東西。我已經根據您的意見在問題中添加了上面的代碼,它應該是什麼樣子?仍然不會爲我獲取多個品牌。 – 2011-06-08 11:38:51

+0

在更新的代碼中,您只有一個條件,而每個有效品牌應該有一個條件_。 @Warren Burton提出了幾乎相同的方法,以更復雜(但也許更合適)的方式動態構建複雜的NSPredicate。 – Gobra 2011-06-08 16:30:50

2

對於那些誰感興趣的雨燕!

let arrPred = [NSPredicate(format: "yourAttribute LIKE %@", toCompareID), NSPredicate(format: "yourAttribute2 LIKE %@", toCompareID2)] //Add as many predicates you want in short make your query 

let compoundpred:NSPredicate = NSCompoundPredicate(andPredicateWithSubpredicates: arrPred) 
var arrFiltered = yourArray.filteredArrayUsingPredicate(compoundpred)