2011-12-05 28 views
6

因此,我成功实现了Core Data以从服务器检索对象,将它们保存并显示在UITableView中。但是现在,我想把这些分成几个部分。我已经看了几天,NSFetchedResultsController似乎混淆了我,即使我使用它的方式工作。在我的Entity中有一个名为“articleSection”的关键字,当项目被添加到核心数据中时,项目被设置为“Top”“Sports”“Life”。我将如何将这些分解成UITableView中的单独部分?我已阅读有关使用多个NSFetchedResultsControllers,但我对此可能会感到沮丧。iPhone - 使用NSFetchResultsController将核心数据分解为多个部分

任何建议或帮助将不胜感激。

+0

查看这个线程http://stackoverflow.com/questions/8037588/sectionindextitlesfortableview-keys-are-off/8037745#8037745我的答案。 希望得到这个帮助。 – iamsult

回答

17

documentation for NSFetchedResultsController有完美的示例代码。

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

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

    UITableViewCell *cell = /* get the cell */; 
    NSManagedObject *managedObject = [self.fetchedResultsController objectAtIndexPath:indexPath]; 
    // Configure the cell with data from the managed object. 
    return cell; 
} 

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { 
    id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:section]; 
    return [sectionInfo name]; 
} 

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView { 
    return [self.fetchedResultsController sectionIndexTitles]; 
} 

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index { 
    return [self.fetchedResultsController sectionForSectionIndexTitle:title atIndex:index]; 
} 

设置读取请求的sortDescriptors这样的成绩是由articleSection排序。
将sectionKeyPath设置为“articleSection”,以便NSFetchedResultsController为您创建节。事情是这样的:

NSFetchRequest *request = [[NSFetchRequest alloc] init]; 
request.entity = [NSEntityDescription entityForName:@"Item" inManagedObjectContext:self.managedObjectContext];; 
request.fetchBatchSize = 20; 
// sort by "articleSection" 
NSSortDescriptor *sortDescriptorCategory = [NSSortDescriptor sortDescriptorWithKey:@"articleSection" ascending:YES]; 
request.sortDescriptors = [NSArray arrayWithObjects:sortDescriptorCategory, nil];; 

// create nsfrc with "articleSection" as sectionNameKeyPath 
NSFetchedResultsController *frc = [[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:self.managedObjectContext sectionNameKeyPath:@"articleSection" cacheName:@"MyFRCCache"]; 
frc.delegate = self; 
NSError *error = nil; 
if (![frc performFetch:&error]) { 
    NSLog(@"Unresolved error %@, %@", error, [error userInfo]); 
    abort(); 
} 
self.fetchedResultsController = frc; 
+0

如果我不想使用NSFetchedResultsController,我该如何做到这一点? – acecapades

相关问题