I have a variable called "conteggio" in my code, you can see it below... this variable have to increase of 1 at every row of my tableview... when i try to do this i receive a result like: 4,8,12,16,etc. multiples of 4 for each row... it seems that it repeat the code 4 times for each row.
And if i scroll back and forth my table those numbers become multiples.
HERE IS MY CODE:
-(UITableViewCell *)tableV开发者_运维百科iew:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellID"];
if (cell == nil){
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"cellID"] autorelease];
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cellID"];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
NSString *alphabet = [fevIndice objectAtIndex:[indexPath section]];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF beginswith[c] %@", alphabet];
NSArray *fv = [fev filteredArrayUsingPredicate:predicate];
conteggio++;
NSString *string = [NSString stringWithFormat:@"%d", conteggio];
cell.detailTextLabel.text = string;
if ([fv count]>0) {
NSString *cellValue = [fv objectAtIndex:indexPath.row];
cell.textLabel.text = cellValue;
//indexPath.section; //[fv count] numero di elementi in una section;
//cell.detailTextLabel.text = [fevMesi objectAtIndex:conteggio];
//cell.imageView.image = [UIImage imageNamed:[fevIcona objectAtIndex:]];
}
cell.detailTextLabel.numberOfLines = 3;
cell.detailTextLabel.font = [UIFont systemFontOfSize:11.0];
return cell;
}
Use indexPath.row to get the row number that it's calling for. Like Jonathan said, the method could be called any number of times so don't try to keep track of the row yourself.
There's no contract concerning how many times that method will be called for each render. Just ask indexPath
for its terminal index.
As the others have already mentioned, cellForRowAtIndexPath can get called multiple times for each row whenever the table view needs to display the cell (eg. when it scrolls into view).
Do you have multiple sections in your table view?
Is conteggio supposed to be the "absolute" unique row number regardless of the section?
If each section has the same number of rows, then it's a simple formula to calculate the absolute row number.
However, if every section has a differnt number of rows, you can calculate the absolute row number by doing something like the following:
conteggio = 0;
for (int s = 0; s < indexPath.section; s++)
{
conteggio += [tableView numberOfRowsInSection:s];
}
conteggio += indexPath.row + 1;
If possible, it might be better for you to redesign fevMesi so the objects in there can be retrieved using row and section instead of having to calculate an absolute row number every time.
精彩评论