2014-02-10 55 views
2

我對排序我的NSFetchedResultsController有一個小問題。我的NSManagedObject有兩個屬性。 datestartTimeCoreData NSFetchedResultsController排序

date對我的所有物體都是時間00:00:00,這樣當使用date作爲sectionNameKeyPath時,它會將具有相同日期(按天)的所有對象抓取到一個部分中。如果日期的時間不同,它會將每個對象放入不同的部分。

這很好,但然後在每個組內,我想通過startTime排序對象。因此,他們從date到最新的每個部分的最早列表。

我的問題是當使用date作爲sectionNameKeyPathstartTime作爲NSSortDescriptor`它不喜歡它並且奇怪地玩。比如只是有時以某種不規則的方式顯示某些數據。

我認爲這歸結爲必須使排序描述符和sectionNameKeyPath相同。我在想這個嗎?如果不是,我應該如何設置我的NSFetchedResultsController以提到的方式列出我的數據?

謝謝。

編輯:這裏是代碼...使用startTime作爲我的第二個排序描述符時也值得注意,它會導致重複顯示在我的tableview與零對象。

NSFetchedResultsController

NSSortDescriptor *sortDescriptor1 = [[NSSortDescriptor alloc] initWithKey:@"date" ascending:YES]; 
    NSSortDescriptor *sortDescriptor2 = [[NSSortDescriptor alloc] initWithKey:@"startTime" ascending:YES]; 
    NSArray *sortDescriptors = @[sortDescriptor1, sortDescriptor2]; 

    [fetchRequest setSortDescriptors:sortDescriptors]; 

    // Edit the section name key path and cache name if appropriate. 
    // nil for section name key path means "no sections". 
    NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:@"date" cacheName:@"Master"]; 

cellForRowAtIndexPath只是展示我如何指定各管理對象的一個​​片段:

id <NSFetchedResultsSectionInfo> sectionInfo = [self.flightFetchedResultsController.sections objectAtIndex:indexPath.section]; 
    NSArray *sectionFlights = [sectionInfo objects]; 
    Flight *flight = [sectionFlights objectAtIndex:indexPath.row]; 

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{ 
    return self.flightFetchedResultsController.sections.count; 
} 

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    id <NSFetchedResultsSectionInfo> sectionInfo = [[self.flightFetchedResultsController sections] objectAtIndex:section]; 
    return [sectionInfo numberOfObjects]; 
} 
+0

顯示一些代碼。 'startTime'是一個字符串嗎? (讓它成爲約會)。 – Wain

+0

這是一個日期,代碼傳入... –

+0

你正在得到錯誤的對象。我會更新我的答案。 – Fogmeister

回答

5

你的部分鍵名路徑需要匹配第一排序描述符。

所以,你可以做...

// sectionKeyNamePath = @"date". 

NSSortDescriptor *dateSD = [NSSortDescriptor sortDescriptorWithKey:@"date" ascending:YES]; 
NSSortDescriptor *startTimeSD = [NSSortDescriptor sortDescriptorWithKey:@"startTime" ascending:YES]; 

frc.request.sortDescriptors = @[dateSD, startTimeSD]; 

如果這樣做,那麼它會排序(和部分)按日期,然後排序開始時間每個部分。

從您的代碼

錯誤收到所獲取的對象。

得到你需要使用一個對象...

Flight *flight = [self.frc objectAtIndexPath:indexPath]; 

已取得的成果控制器知道關於它的章節和行。你不需要拆分它。

+0

有趣,但這會導致一些奇怪的結果。比如在我的tableview中沒有重複。我已經向OP添加了代碼。 –

+0

我不這麼認爲,根據您的建議獲取Flight對象只會從第一部分(第一組對象)中抽取經驗。因此,對於表中的每個部分,您需要獲取相應的部分對象。不過,我覺得我可能已經解決了這個問題,但總的項目清理已經完成了。感謝匹配第一個排序描述符的提示,儘管我不知道! –

+0

索引路徑指向部分和行。它是如何工作的。這不是我相信它是如何工作的,而是它的工作原理。很高興你把它分類。 – Fogmeister

相關問題