tags:

views:

39

answers:

2

I'd done following code, on which I get repeat result from 10 index. (indexPath.row)

my data is in Dictionary What could be the reason?

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSUInteger index = indexPath.row;    
NSLog(@"Current cell index : %d",index);
static NSString *CellIdentifier = @"CellIndetifier";
BOOL isCellSelected = NO;
//ListViewCell *cell = (ListViewCell *)[table dequeueReusableCellWithIdentifier:CellIdentifier];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil) {        
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewStylePlain reuseIdentifier:CellIdentifier] autorelease];
    NSString * text = nil;
    if(isMultipleSelect){            
        text = [dicData objectForKey:[sortedData objectAtIndex:index]];
        if([sIndexes containsObject:[sortedData objectAtIndex:index]]){
            isCellSelected = YES;                
        }
    }
    cell.textLabel.text = text;

}    
return cell;

}

+3  A: 

You get wrong result because you setup cell's text only when it is created, while the same cell can be used for several different rows. You need to move text-setting code outside of the creating cell block:

if (cell == nil) {        
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewStylePlain reuseIdentifier:CellIdentifier] autorelease];
}

NSString * text = nil;
if(isMultipleSelect){            
    text = [dicData objectForKey:[sortedData objectAtIndex:index]];
    if([sIndexes containsObject:[sortedData objectAtIndex:index]]){
        isCellSelected = YES;                
    }
}
cell.textLabel.text = text;  
Vladimir
ahhh.. I thought that, I'll get correct cell by dequeueReusableCellWithIdentifier
Pravat Maskey
Thank you :) Vladimir
Pravat Maskey
A: 

You need to refactor the code like this:

if (cell == nil) {        
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewStylePlain reuseIdentifier:CellIdentifier] autorelease];
}

NSString * text = nil;
if(isMultipleSelect){            
    text = [dicData objectForKey:[sortedData objectAtIndex:index]];
    if([sIndexes containsObject:[sortedData objectAtIndex:index]]){
        isCellSelected = YES;                
    }
}
cell.textLabel.text = text;

The if (cell == nil) path is to allocate a new cell if dequeueReusableCellWithIdentifier: didn't return anything. The rest of the code needs to be same for both cases: set up the cell.

DarkDust