aherlambang
aherlambang

Reputation: 14418

pushViewController at didSelectRowAtIndexPath

I have the following code:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here. Create and push another view controller.
     if (tvc == nil)
     tvc = [[TopicViewController alloc] initWithNibName:@"TopicViewController" bundle:nil];
     tvc.title = @"Topic";
     tvc.topicId = [[results objectAtIndex:indexPath.row] objectForKey:@"id"];
     // ...
     // Pass the selected object to the new view controller.
     [self.navigationController pushViewController:tvc animated:YES];
     [tvc release];

}

So when I tap on the row it is able to bring this table view. Then I press navigate back and choose a different row, then the app crashes. I tried to see in the console for any error, but can't find any. What is wrong?

Upvotes: 2

Views: 2541

Answers (4)

MHC
MHC

Reputation: 6405

Assuming tvc is a declared property that retains an object, do

self.tvc = [[TopicViewController alloc] initWithNibName:@"TopicViewController" bundle:nil];
//....
self.tvc = nil;
[tvc release];

instead of

tvc = [[TopicViewController alloc] initWithNibName:@"TopicViewController" bundle:nil];
//....
[tvc release];

However, I wouldn't release the view controller and re-allocate it at all, because a memory allocation is expensive. I would just store one tvc object and reuse it, by modifying it according to the selected row.

Upvotes: 0

Yorxxx
Yorxxx

Reputation: 526

You're always releasing, even if it's not allocated.

Upvotes: 0

Robin
Robin

Reputation: 10011

@Equinox i think you need to do something like this

 tvc.title = [[NSString alloc] initWithFormat:@"Topic"];
 tvc.topicId = [[NSString alloc] initWithString:[[results objectAtIndex:indexPath.row] objectForKey:@"id"]];

Edit: i think you are over releasing some objects in your TopicViewController class so your app is getting crash with out any message in the console. what you can do is build and analyze your project to check for any over releasing objects

Upvotes: 0

Rog
Rog

Reputation: 18670

I believe your (tvc == nil) is returning NO because you released tvc but didn't set it to nil so next time this method is accessed, you try and push it as a view controller without allocating it again, hence the crash.

You can either remove the if (tvc == nil) check or release tvc and then set it to nil with [tvc release], tvc = nil;.

The other possibility is your results array is being released. Where is it initialised and have you declared a retain property for it? If so you can access it with [self.results objectAtIndex:...] which will guarantee it will stick around until your view controller is deallocated.

Upvotes: 3

Related Questions