2011-12-19 26 views
2

我正在使用NSFetchedResultsController來填充我的應用程序的tableView它是逐個分組(在這種情況下,我的核心數據對象中的類別屬性)我想手動重新排序該部分不按字母順序。下面排序核心數據中的特定部分

是我迄今所做的提前

- (NSFetchedResultsController *)fetchedResultsController { 

if (_fetchedResultsController != nil) { 
    return _fetchedResultsController; 
} 

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; 
NSEntityDescription *entity = [NSEntityDescription 
           entityForName:@"Media" inManagedObjectContext:_context]; 
[fetchRequest setEntity:entity]; 

NSSortDescriptor *sort = [[NSSortDescriptor alloc] 
          initWithKey:@"category" ascending:NO]; 
[fetchRequest setSortDescriptors:[NSArray arrayWithObject:sort]]; 

[fetchRequest setFetchBatchSize:20]; 

NSFetchedResultsController *theFetchedResultsController = 
[[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest 
            managedObjectContext:_context sectionNameKeyPath:@"category" 
               cacheName:@"Root"]; 
self.fetchedResultsController = theFetchedResultsController; 
_fetchedResultsController.delegate = self; 

return _fetchedResultsController;  

} 

感謝代碼!

回答

2

如果任務是提供部分的客戶訂單,比你也可以繼承NSFetchedResultsController和實施

- (NSInteger)sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)sectionIndex; 

,如果需要

@property (nonatomic, readonly) NSArray *sectionIndexTitles; 
- (NSString *)sectionIndexTitleForSectionName:(NSString *)sectionName; 
2

您可以添加一個名爲MediaCategory一個新的實體:

  • 屬性name
  • 屬性rank
  • 一對多的關係media到實體Media

並更換category屬性與到MediaCategory的關係。

然後,您可以用下面的各種描述符請求的結果進行排序:

fetchRequest.sortDescriptors = 
[NSArray arrayWithObjects: 
[[NSSortDescriptor alloc] initWithKey:@"category.rank" ascending:NO], 
[[NSSortDescriptor alloc] initWithKey:@"category.name" ascending:NO], // required only if many categories have the same rank 
nil]; 

,並提供@"category.name"作爲結果控制器的sectionNameKeyPath