2014-02-16 67 views
0

我試圖根據我的屬性(類似於iOS通訊簿應用程序)上的第一個字母顯示我的核心數據模型的值到A-Z索引表。我的核心數據模型的「收藏夾」實體有2個屬性:用戶名和狀態。我只想顯示帶有status = accepted的用戶名到A-Z索引表。 這裏是我的代碼:ios核心數據到AZ索引tableview

- (NSFetchedResultsController *)fetchedResultsController { 

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

NSManagedObjectContext *managedObjectContext = [self managedObjectContext]; 

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

NSString *status = @"accepted"; 
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"status == %@",status]; 
[fetchRequest setPredicate:predicate]; 

// Create the sort descriptors array. 
NSSortDescriptor *usernameDescriptor = [[NSSortDescriptor alloc] initWithKey:@"username" ascending:YES]; 
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:usernameDescriptor, nil]; 
[fetchRequest setSortDescriptors:sortDescriptors]; 

// Create and initialize the fetch results controller. 
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContext sectionNameKeyPath:@"username" cacheName:@"Root"]; 
self.fetchedResultsController = aFetchedResultsController; 
fetchedResultsController.delegate = self; 

return fetchedResultsController; 
} 

現在,當我試圖訪問該節的名稱,我得到(空)

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section 
{ 
    NSLog(@"%@",[[[fetchedResultsController sections] objectAtIndex:section] name]); 
    return [[[fetchedResultsController sections] objectAtIndex:section] name]; 
} 

而且我的事,與這樣,我將得到的名稱和不是第一個字符爲了顯示它作爲部分標題。

回答

1

您需要正確地訪問sectionsInfo對象:

id <NSFetchedResultsSectionInfo> info = 
    [fetchedResultsController sections][section]; 
return [info name]; 

然而,這會給你爲每一個獨特的名字標題,可能不希望你想要的。相反,您必須爲您的實體提供臨時財產NSString *sectionIdentifier併爲它寫一個getter,它返回用戶名屬性的第一個字母。

如果想從A-Z索引在表格右側邊緣跑下來查看您還必須實現:

sectionIndexTitlesForTableView:
tableView:sectionForSectionIndexTitle:atIndex:

如果你的標題仍然有null,可能它們沒有設置或持續在你的實體中?也許你得到零結果?也許你的fetchedResultsController是nil?數據模型中存在一些缺陷,所以這似乎很有可能。

  • 您的實體名稱Favorites是複數。這是不合邏輯的,你應該把它命名爲Favorite,因爲一個實例只描述一個最喜歡的。
  • 狀態是一個非常低效的字符串。相反,你應該使用一個數字並應用一些枚舉方案。
  • 用戶名是Favorite的財產。這似乎也很混亂,因爲大概你也有一個User實體,它具有username屬性。您應該使用關係來對此進行建模。
+0

謝謝你的回答,依舊如果我把你的代碼中titleForHeaderProperty和NSLog的[信息名]我得到空值內.. –

+0

我加還有一些建議。 – Mundi