Lorenzo
Lorenzo

Reputation: 447

Cocoa - UITableViewController strange behaviour !

I'm losing my mind on this:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *MyIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier]; 

    UILabel *label;

    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease];
        label=[[UILabel alloc]initWithFrame:CGRectMake(20, 20, 200, 30)];
        [cell addSubview:label];
        [label setText:[NSString stringWithFormat: @"%d",indexPath.row]];
    }

    return cell;
}

in the cells' labels, i see this numbers instead of the progression I am expecting (0,1,2,3,4...):

0 1 2 0 4 1 2 0 4 1

any idea where's the error? Seems I can't figure this out.

EDIT resolved after putting the initialization of the label after the cell==nil{} block.(don't know why i put that there in the first place.)

Upvotes: 0

Views: 149

Answers (2)

odrm
odrm

Reputation: 5249

You need to perform cell configuration outside of the if:

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier]; 
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease];
    UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(20, 20, 200, 30)];
    [cell addSubview:label];
    [label release];
}   

[label setText:[NSString stringWithFormat: @"%d",indexPath.row]];

Oh - and you should release the label after adding it to avoid a memory leak :)

Upvotes: 2

Chetan Bhalara
Chetan Bhalara

Reputation: 10344

Try this

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

{

static NSString *MyIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];

UILabel *label;

if (cell == nil)

{

   cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease];

}

label=[[UILabel alloc]initWithFrame:CGRectMake(20, 20, 200, 30)];

[cell addSubview:label];

[label setText:[NSString stringWithFormat: @"%d",indexPath.row]];

[label release];

return cell;

Upvotes: 0

Related Questions