2012-10-11 50 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 

} 

如果有人有更好的解决办法...