2011-04-09 64 views
0

我已經瀏覽了很多帖子,仍然不知道如何解決這個問題。希望有人能幫忙。使用NSSet關係來填充cellForRow

它一直運行,直到碰到最後一個數據源方法cellForRow。 在這一點上,我可以得到每個部分正確的NSSet,但無序。對行關係屬性的intropection如何工作?

在cellForRow中使用字符串字面值我在每個部分都得到了正確數量的行,但顯然沒有連接到將存在的管理對象。

如何填充NSSet關係中的行?所有Insight讚賞

類別< < --- >>人
CNAME ---------- PNAME

關係
人----------類別

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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section  { 
Category* cat = [[self.fetchedResultsController fetchedObjects] objectAtIndex:section]; 
return [[cat people] count]; 
} 

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { 
Category* cat = [[self.fetchedResultsController fetchedObjects] objectAtIndex:section]; 
NSNumber *rowCount = [NSNumber numberWithUnsignedInteger:[[cat people] count]]; 
return cat.cName; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {  
NSManagedObject *mo = [[fetchedResultsController fetchedObjects] objectAtIndex:index.row]]; 

// returns the correct set but unordered, possibly work with this to populate the rows? 
//NSSet *theSet = [[NSSet alloc] initWithSet: [mo valueForKeyPath:@"people.pName"]]; 

// doesn't work 
// cell.textLabel.text = [NSString stringWithFormat:@"%@",[mo valueForKeyPath:@"people.pName"]]; 

cell.textLabel.text = @"something"; 
return cell; 
} 

回答

0

您的問題是,您正在提取Category對象,但您嘗試使用Person對象設置您的行。 Person對象是無序的,因爲它們不是獲取的對象。它們與tableview的邏輯結構沒有任何關係。事實上,他們不能這樣做,因爲他們與Category有多對多的關係,這樣同一個對象可以在同一個表中多次出現。

最好的解決辦法是把它分解成兩個等級表。一個顯示「類別」列表,第二個顯示對象與第一個表格視圖中選擇的Category對象的people關係。

您可以嘗試把它與當前的設計工作,試圖像:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    Category *sectionCategory=[[fetchedResultsController fetchedObjects] objectAtIndex:indexPath.section]; 
    NSSortDescriptor *sort=[NSSortDescriptor sortWithKey:@"pname" ascending:NO]; 
    NSArray *sortedPersons=[sectionCategory.people sortedArrayUsingDescriptors:[NSArray arrayWithObject:sort]]; 
    Person *rowPerson=[sortedPersons objectAtIndex:indexPath.row]; 
    cell.textLabel.text = rowPerson.pname; 

,如果你的數據是靜態的這工作。如果它在表格顯示時發生變化,您將遇到麻煩。它會有一些開銷,因爲每次填充一行時,您都必須對sectionCategory對象的所有Person對象進行提取和排序。

我強烈推薦兩個tableview解決方案。這是分層數據的首選解決方案。

+0

非常感謝您的意見。如果我理解正確,我希望以首選方式進行此操作,並且實際上沒有問題顯示一個列表並推送相關對象。我想看看所有人都會看起來如何。當我嘗試這些代碼時,我得到了一個'sortWithKey'發送的'無法識別的sel:你能想出任何合理的方法來做到這一點,也許創建字典來飼料電視或什麼? – rube 2011-04-11 03:15:20

+0

很可能我在'sortWithKey'中得到了屬性名稱錯誤。被排序的對象必須具有'pname'屬性。如果我誤解了你的模型,只需要替換適當的屬性名稱即可。 – TechZen 2011-04-11 17:13:56

+0

TechZen - 是的,對不起,我意識到發佈評論後,它只是一個名稱問題。(我發佈的代碼有點偏離,我的錯)你說得對。我感謝你的建議和時間,並幫助我們尋找其他更好的方法來完成我在這裏嘗試的事情。再次感謝! – rube 2011-04-11 23:00:41