I am unable to access my NSMutableArray in didSelectRowAtIndexPath although i am able to access it in cellForRowAtIndexPath.
Here is my code :-
- (void)viewDidLoad
{
NSString *path = [[NSBundle mainBundle] pathForResource:@"drinks" ofType:@"plist"];
self.drinkArray = [[NSMutableArray alloc] initWithContentsOfFile:path];
NSLog(@"%@", self.drinkArray);
[super viewDidLoad];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
NSLog(@"I am inside cellForRowAtIndexPath");
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell.
NSDictionary *dict = [self.drinkArray objectAtIndex:indexPath.row];
cell.textLabel.text = [dict objectForKey:@"name"];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
[dict release];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
DrinkDetails *detailViewController = [[DrinkDetails alloc] initWithNibName:@"DrinkDetails" bundle:nil];
// ...
// Pass the selected object to the new view controller.
//detailViewController.drink = [self.drinkArray objectAtIndex:indexPath.row];
NSLog(@"%@", self.drinkArray);
[self.navigationController pushViewController:detailViewController animated:YES];
[detailViewController release];
}
Sometime NSLog prints some stupid output and sometime it gives me an error “EXC_BAD_ACCESS”.
Please take a look and check what is wrong with my code.
Any help would be appreciated.
Thanks.
You have one (really two) issues, but the main one is in your
-cellForRowAtIndexPath:method:Get rid of this line and it should work just fine.
The reason why this fixes your issue is because
-objectAtIndex:simply returns a pointer to the requested object in memory, therefore you do not (and should not) send the-releasemessage to that object because theNSArrayobtained ownership of the object when it was inserted. Sending-releaseto this object reference effectively deallocates the object in memory and now this indice in theNSArrayis pointing to garbage memory. BAD BAD BADThe other issue is that you have a memory leak here:
You are sending the
-retainmessage to an object reference that you already have ownership of by way of sending-alloc. (This of course assumes that your@propertyhas theretainsetter modifier)To fix this issue, simply send the
-autoreleasemessage to this instance: