2014-07-17 37 views
1

我有以下數據模型:NSFetchedResultController複雜的排序情況

[Agency] <--->> [AgencyRating] <<---> [RatingType] 

還有的rating types號(前整體,品牌,設計,編程等)。每個agency可以具有所有這些評級類型(例如,agency FooBar在設計中有1050個點,在品牌方面有700個點)。

表結構:

Agency:名稱:字符串 RatingType:名稱:字符串 AgencyRating:agency_ref:關係agency,ratingType_ref:關係rating type,值:整數。

我有拆分視圖控制器。左側包含可用的rating types。當用戶選擇任何評級類型時,我想按右側的評級值代理機構進行排序。我想用NSFetchedResultController來實現它。我瞭解如何獲得評分值以在單元格中顯示它,但我不明白如何創建排序描述符。

目前我有:

控制器:

_contentFetchController = [Agency MR_fetchAllGroupedBy:nil withPredicate:[NSPredicate predicateWithValue:YES] sortedBy:@"name" ascending:YES]; 

細胞:

- (void) configureForAgency:(Agency *) agency ratingType:(RatingType *) ratingType forIndexPath:(NSIndexPath *) path { 
    self.positionLabel.text = [NSString stringWithFormat: @"%d", (int)path.row + 1]; 

    UIImage *image = [UIImage imageWithContentsOfFile:agency.logoPath]; 
    if (image) { 
     self.logoImageView.image = image; 
    } 

    self.nameLabel.text = agency.name; 

    // HERE IS VALUE OF RATING 
    self.ratingValueLabel.text = [[agency ratingForRatingType:ratingType] stringValue]; 
} 

正如你所看到的:我按名稱排序,但我需要的等級值進行排序,根據在選定的評級類型上。有任何想法嗎?

回答

2

爲了做到這一點,您需要獲取Agencies,其中有一個關聯的AgencyRating與選定的評級類型,並按評級值排序所有內容。

我假設評分類型是ratingType,評分值是ratingValueAgencyRating協會是agencyRatings。我還假設每個機構只能對每個評級類型只有一個機構評級(如果沒有,您將不得不按所選機構所有機構評級的總和進行排序)。

通過MR_前綴判斷,我猜你正在使用我不熟悉的MagicalRecord,但以下是如何使用普通的NSFetchRequestNSFetchedResultsController來做到這一點。

首先,你需要建立一個NSFetchRequest

NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Agency"]; 
fetchRequest.predicate = [NSPredicate predicateWithFormat:@"ANY agencyRatings.ratingType = %@", ratingType]; 
fetchRequest.sortDescriptors = @[ [NSSortDescriptor sortDescriptorWithKey:@"agencyRatings.ratingValue" ascending:YES] ]; 

然後你可以設置NSFetchedResultsController像平時不向它提供fetchRequest剛創建。

每當用戶改變ratingType你需要改變fetchRequestpredicate並在fetchedResultsController調用performFetch

我想你需要調整這一點以適應你的情況,但想法是有一個謂詞和排序描述符指向一個相關的表。

+1

將無法​​正常工作,因爲'sortDescriptorWithKey:@「agencyRatings.ratingValue」'將生成:'這裏不允許的對多密鑰' – user2786037

+0

是的,沒錯,忘了它:) –

+0

據我瞭解,只有一個解決方案:使用tableView和數組作爲數據源,並使用原始sql查詢填充該數組。但我希望有另一種解決方案:) – user2786037