2012-10-11 78 views
1

在Apple Development論壇上有關於爲大型行集合手動計算表視圖部分的討論。對於視覺效果,需要一個開發者賬戶:手動計算UITableView部分

NSFetchedResultsController fetching all objects in the DB...

要重新擔負對於那些沒有開發的帳戶,蘋果技術人員建議使用實體包含索引標題,與一對多的關係,實體要顯示成排。

典型的例子是歌曲或藝術家,其中索引部分標題的第一個字母A,B,C ...

所以,標題爲一個實體將有一個一對多的關係的集合以字母A開頭的歌曲,等等。

該機制是使用提取的結果控制器來檢索所有歌曲,並且同時啓動用於檢索索引的NSArray的提取請求。

NSFetchRequest *req = //fetch request for section entity 
NSArray *sections = [MOC executeFetchRequest:req error:&error]; 

這是很容易得到部分分段數和行:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { 
    // Return the number of sections. 
    NSInteger abc = [self.sections count]; 
    return abc; 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 
    CardSection *s = (CardSection*)[self.sections objectAtIndex:section]; 
    NSInteger rows = [s.cards count]; 
    return rows; 
} 

-(NSString*)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { 
    CardSection *s = [self.sections objectAtIndex:section]; 
    NSString *title = s.title; 
    return title; 
} 

然而,問題在指數路徑在小區開始爲行:

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

    NSManagedObject obj = [_fetchedResultsController objectAtIndexPath:indexPath]; 
    // build cell....  
    return cell; 
} 

因爲很明顯,索引路徑被稱爲計算部分和行,因此取出的控制器超出範圍。

當然,這可以通過調用section實體並要求NSSet關係中的特定索引對象來解決,但這樣就失去了獲取控制器的好處。

我想知道是否有人嘗試過這種方法,他是如何設法解決這個問題的。

+0

[手動]向上滾動你的'UITableView'和計數'sections' :) – Hemang

+0

雖然我可以自己做[手動],但是一旦應用出貨,我就不會向我的客戶提問:-) – Leonardo

回答

0

我到目前爲止發現的唯一解決方案是發佈解析節數組以查找特定索引處的前一個對象的數量。

 int latestCount=0; 
     // BOX_INT is just a personal macro for converting something to NSNumber 
     self.totalAtIndex=[NSMutableDictionary dictionaryWithCapacity:0]; 
     [self.totalAtIndex setObject:BOX_INT(0) forKey:BOX_INT(0)]; 
     for (int i=1;i<[self.sections count];i++) { 
      CardSection *cardSection = [self.sections objectAtIndex:i-1]; 
      latestCount = latestCount + [cardSection.cards count]; 
      [self.totalAtIndex setObject:BOX_INT(latestCount) forKey:BOX_INT(i)]; 
     } 

例如假設這是我的部分,其中[A,B]只是NSIndexPath:

[0,0][0,1] (2 objects) 
[1,0]  (1 object) 
[2,0][2,1] (2 object) 

如果我在指數2,[self.totalAtIndex objectAtIndex:2]會包含在索引0 +索引1之前存儲的對象的數量,因此返回3. 索引[2,1]被轉換爲[0,5]。

這是記者cellForRow:atIndexPath:

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

    // hack index path 
    NSInteger section = indexPath.section; 
    NSInteger row = indexPath.row; 

    int howManyBefore = [[self.totalAtIndex objectForKey:BOX_INT(section)] intValue]; 
    NSIndexPath *newIndexPath = [NSIndexPath indexPathForRow:row+howManyBefore inSection:0]; 

    NSManagedObject *obj = [_fetchedResultsController objectAtIndexPath:newIndexPath]; 

    // build and return cell 

} 

如果有人有更好的解決辦法...