我是xcode的新手,我执行此代码是为了用注释标题填充表视图,但该函数被多次调用,并且表格单元格中填充了所有重复的值,如何在xcode中调用该函数,如何阻止该函数被多次调用
- (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] autorelease];
}
NSLog(@"this is a test text ");
NSMutableArray *annotations = [[NSMutableArray alloc] init];
int i=0;
if(indexPath.section == 0)
{
for(iCodeBlogAnnotation *annotation in [map annotations])
{
i++;
NSLog(@"this is the no %d",i);
[annotations addObject:annotation];
}
cell.textLabel.text = [[annotations objectAtIndex:indexPath.row] title];
}
return cell;
}
如有任何帮助,我们将不胜感激,提前感谢您的帮助
发布于 2011-06-15 00:36:31
你不能真正控制它什么时候被调用。每当你的tableview想要显示一个新的单元格时,它就会被调用。您可以使用indexPath来确定要放入该单元格中的内容。对于屏幕上的每个单元格,它至少调用一次(如果上下滚动表格,有时会调用更多)。
您不需要在每次调用此函数时都创建临时数组,只需直接使用[map annotations]
:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// There will be one row per annotation
return [[map annotations] count]
}
- (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] autorelease];
}
// Put the text from this annotation into this cell
cell.textLabel.text = [[[map annotations] objectAtIndex:indexPath.row] title];
return cell;
}
我希望我已经理解了你的问题。如果没有,请在下面的评论中告诉我!
发布于 2011-06-15 00:37:48
它不是一个函数,而是一个方法。
它在表格视图绘制单元格时由表格视图调用。它将被每个单元格调用一次,有时,根据用户正在做的事情,每个单元格调用不止一次。
您不会将数据推送到表视图中,它会要求您提供单元格内容。
询问“我如何才能阻止这个函数被多次调用?”表示您不理解表视图(如果您来自UI编程的“推送”模型,这会令人困惑)。从TableView programming guide开始。
发布于 2011-06-15 00:39:12
只要UITableView还没有特定索引路径的UITableViewCell并且需要一个,就会调用该函数。请注意,由于用户滚动(为了节省内存,屏幕外的单元格可能会被重用或释放)或对reloadData
和相关函数或insertRowsAtIndexPaths:withRowAnimation:
和相关函数的调用,可能会对索引路径调用多次。您不能(也确实不想)阻止它被多次调用。
也就是说,假设[map annotations]
返回某种排序的有序集合,并且每次都以相同的方式排序,那么您的代码应该可以执行您想要的操作(即使它的效率非常低)。关于这个问题的更多细节将是有帮助的。
https://stackoverflow.com/questions/6346832
复制相似问题