1

我在使用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時

尼克

回答

0

nil爲您sectionNameKeyPath

如果傳遞name,基本上你說:「請爲每一個名字一個部分」。當通過nil時,您告訴它只創建一個部分。

您實現代碼如下方法實現看我的權利。

[_fetchedResultsController sections]爲您提供與您可以要求之類的物體的一個部分數量對象的數組。相比之下,[_fetchedResultsController sectionIndexTitles]大多是這樣,你可以告訴NSFetchedResultsController這部分的標題使用(即你將與一個字符串每個部分將其設置爲一個數組)。在你的情況下,你可以忽略它。

+0

嗨,謝謝!但我忘了告訴你,我想要在音樂應用程序中的部分。 (我想使用名稱的第一個字母作爲部分標題)。那我該怎麼做?對不起英文不好。 =) – Dafen