我在使用NSFetchedResultsController工作時遇到問題。我有一個實體,說'員工'和一個字符串屬性,讓我們說'名字'。現在我想告訴所有員工的名字中使用NSFetchedResultsController ......沒問題的一個UITableView,我的繼承人代碼:NSFetchedResultsController - >如何實現節?
if (_fetchedResultsController == nil) {
NSManagedObjectContext *moc = [appDelegate managedObjectContext];
NSFetchRequest *request = [NSFetchRequest new];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Employee" inManagedObjectContext:moc];
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
[request setEntity:entity];
[request setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];
_fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:moc sectionNameKeyPath:@"name" cacheName:@"root"];
NSError *error;
[_fetchedResultsController performFetch:&error];
if (error != nil) {
NSLog(@"Error: %@", error.localizedDescription);
}
}
但NSFetchedResultsController創建爲每個實體的部分。所以當我有200名員工時,它會創建200個部分。爲什麼?
我如何正確地實現這些methords:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return [[_fetchedResultsController sections] count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [[[_fetchedResultsController sections] objectAtIndex:section] numberOfObjects];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// Configure the cell...
cell.textLabel.text = [[_fetchedResultsController objectAtIndexPath:indexPath] valueForKey:@"name"];
return cell;
}
可能我明白整個概念錯了嗎? [_fetchedResultsController各節]和[_fetchedResultsController sectionIndexTitles]之間的區別在哪裏?
我希望你能幫助我,在此先感謝!
編輯:我忘了告訴你,最重要的事情:我想有由「name」屬性的第一個字母分離的部分。 (就像音樂APP)。初始化您NSFetchedResultsController時
尼克
嗨,謝謝!但我忘了告訴你,我想要在音樂應用程序中的部分。 (我想使用名稱的第一個字母作爲部分標題)。那我該怎麼做?對不起英文不好。 =) – Dafen