對於我的生活,我似乎無法得到這個工作。你如何構造NSFetchRequest的setHavingPredicate謂詞?
假設我們的實體是一個具有狀態字段和訂單字段的管理對象。
我該如何處理讓所有有序訂單具有多個相同的訂單?
請不要告訴我只要在主謂語中使用@count做子查詢,因爲我知道這個解決方案,這篇文章的重點是要理解如何在覈心數據中使用謂詞,反正可能比子查詢更快。 (除非你解釋爲什麼我不能使用having子句)
以下代碼將返回帶有每個訂單號的訂單數量的字典數組。我想要的是能夠添加一個having子句來限制我的請求,只返回表示那些次數大於1的訂單對象的字典。
這是迄今爲止的代碼,謂:
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"OrderedEntry"
inManagedObjectContext:context];
[fetchRequest setEntity:entity];
[fetchRequest setResultType:NSDictionaryResultType];
NSPredicate *predicate = [NSPredicate predicateWithFormat:
@"(status == %@)",[NSNumber numberWithInt:EntryStatusAlive]];
[fetchRequest setPredicate:predicate];
NSExpression *keyPathExpression = [NSExpression expressionForKeyPath: @"order"]; // Does not really matter
NSExpression *maxExpression = [NSExpression expressionForFunction: @"count:"
arguments: [NSArray arrayWithObject:keyPathExpression]];
NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init];
[expressionDescription setName: @"orderCount"];
[expressionDescription setExpression: maxExpression];
[expressionDescription setExpressionResultType: NSInteger32AttributeType];
[fetchRequest setPropertiesToFetch: [NSArray arrayWithObjects:expressionDescription,@"order",nil]];
[fetchRequest setPropertiesToGroupBy:[NSArray arrayWithObjects:@"order",nil]];
//[fetchRequest setHavingPredicate:[NSPredicate predicateWithFormat:@"@count > 1"]];
//[fetchRequest setHavingPredicate:[NSComparisonPredicate predicateWithLeftExpression:maxExpression rightExpression:[NSExpression expressionForConstantValue:[NSNumber numberWithInteger:1]] modifier:NSDirectPredicateModifier type:NSGreaterThanPredicateOperatorType options:NSCaseInsensitivePredicateOption]];
NSError *error;
NSArray * array = [context executeFetchRequest:fetchRequest error:&error];
你有沒有得到這樣一個答案?我發現了很多對setHavingPredicate的無用參考,它們沒有提供這個謂詞的格式。沒有工作的例子,沒有任何我已經嘗試過的工作... –
@ChristopherKing沒有,我基本放棄了,網上沒有任何信息,而蘋果網絡論壇也沒有多大幫助。我真的相信沒有人會使用它,因爲通過正常獲取然後通過過濾器或通過循環手動移動數據來構建Having謂詞的相同功能非常簡單。我們想知道,因爲總是有'正確的方式'去做某些事情,特別是如果提供了API的話。 – thewormsterror