2015-11-13 40 views
1
let fetchRequest = NSFetchRequest(entityName: "Product") 
    fetchRequest.predicate = NSPredicate(format: "shopItem.wishList == %@", currentWishList) 
    fetchRequest.resultType = .DictionaryResultType 
    fetchRequest.sortDescriptors = [NSSortDescriptor(key: "mainBestPrice", ascending: true)] 
    let minPriceExpression = NSExpression(format: "min:(mainBestPrice)") 
    let minPriceED = NSExpressionDescription() 
    minPriceED.expression = minPriceExpression 
    minPriceED.name = "productPrice" 
    minPriceED.expressionResultType = .DoubleAttributeType 
    fetchRequest.propertiesToFetch = ["shopItem.keyword", "productTitle", minPriceED] 
    fetchRequest.propertiesToGroupBy = ["shopItem.keyword"] 

我想組由一個場NSFetchRequest,但總是出現錯誤:斯威夫特NSFetchRequest組由一個屬性

CoreData: error: Serious application error. Exception was caught during Core Data change processing. This is usually a bug within an observer of NSManagedObjectContextObjectsDidChangeNotification. SELECT clauses in queries with GROUP BY components can only contain properties named in the GROUP BY or aggregate functions

,我應該在組使用的所有字段propertiesToFetch。但我不想這樣做...

+0

沒辦法。您必須將'productTitle'添加到'propertiesToGroupBy',或將其從'propertiesToFetch'中移除。它可能是你可以得到你想要的不同方式:使用Key值編碼集合運算符或NSFetchedResultsController。如果你編輯你的文章以包含實體和關係的細節(一對多,多對多),我相信你會得到一些建議。 – pbasdf

+0

我真的需要所有的領域,你可以告訴我怎麼可以在'''fetchRequest'''之後對結果進行分組? – Arti

回答

2

一個選項是使用NSFetchedResultsController(請參閱Apple Docs)。這通常用於填充表視圖,但也可以用於對CoreData提取的結果進行分組--確定分組。必須按照確保組中所有項目排序在一起的方式對提取進行排序。在你的例子中,你正在分組shopItem.keyword,所以你需要指定shopItem.keyword作爲第一個排序描述符。第二個排序描述符應該是mainBestPrice(升序),以便每個組中的第一個項目是該組中具有最低mainBestPrice的項目。因此,對於FRC的配置會是這個樣子:

let fetchRequest = NSFetchRequest(entityName: "Product") 
fetchRequest.predicate = NSPredicate(format: "shopItem.wishList == %@", currentWishList) 
let keyWordSort = NSSortDescriptor(key: "shopItem.keyword", ascending: true) 
let priceSort = NSSortDescriptor(key: "mainBestPrice", ascending: true) 
fetchRequest.sortDescriptors = [keyWordSort, priceSort]; 
let myFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.managedObjectContext!, sectionNameKeyPath:"shopItem.keyword", cacheName:nil) 
do { 
    try myFetchedResultsController.performFetch() 
} catch let error as NSError { 
    // Replace this implementation with code to handle the error appropriately. 
    print("Unresolved error \(error), \(error!.userInfo)") 
    abort() 
} 

現在,用最低的價格最好的產品將在每節的第一個項目,例如。對於第一部分(即第一shopItem.keyword):

let firstProduct = myFetchedResultsController.sections![0].objects![0] as! Product 

或讓他們的陣列(所有shopItem.keyword S),

let products = myFetchedResultsController.sections!.map() { $0.objects![0] as! Product} 

的NSFetchedResultsController將盡最大努力來優化內存和速度,儘管如果你有大量的話你應該小心。