2016-02-28 88 views
0

這是可能在過濾器中使用聚合函數:核心數據使用聚合函數在過濾器

var expressionDescriptions = [AnyObject]() 
let request = NSFetchRequest(entityName: "Item") 
let expressionDescription = NSExpressionDescription() 
expressionDescription.name = "requestsCount" 
expressionDescription.expression = NSExpression(format: "@sum.requests.id") 
expressionDescription.expressionResultType = .Integer32AttributeType 
expressionDescriptions.append(expressionDescription) 

request.predicate = NSPredicate(format: "requestsCount != sitesCount") 
request.propertiesToFetch = expressionDescriptions 
do { 
    let items = try self.managedObjectContext.executeFetchRequest(request) 
} catch { 
} 

此代碼返回我的錯誤:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'keypath requestsCount not found in entity

回答

1

有隨你怎麼有幾個問題使用NSExpression和相關的API。這很難,也許在你的情況下沒有必要。

假設這個數據結構:

Item (requests) <--->> NSSet? (Request) 
    (sitesCount) Int 

您應該簡單地獲取所有項目,並在內存中進行檢查。這不應該造成任何資源限制問題(如果是這樣,您可以稍後優化):

filteredItems = allItems.filter { ($0.requests?.count ?? 0) != $0.sitesCount } 
相關問題