Help with NSFetchedResultsController
Please help with this issue of using NSFetchedResultsController.
I created an object of NSFetchedResultsController and I use it once in the method: tableView:cellForRowAtIndexPath:
and when I try to execute the same code in the method tableView:didSelectRowAtIndexPath:
I get EXC_BAD_ACCESS
.
Here is the code of the 2 methods
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)inde开发者_开发百科xPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
Person *person = [fetchedResultsController objectAtIndexPath:indexPath];
cell.textLabel.text = person.name; //This works fine
[person release];
return cell;
}
and here is the problematic snippet:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
PhotoListViewController *photoListViewController = [[PhotoListViewController alloc] initWithNibName:@"PhotoListViewController" bundle:nil];
//The next line returns a bad object or undefined memory
Person *person = [fetchedResultsController objectAtIndexPath:indexPath];
//causing the call of [person name] to return EXC_BAD_ACCESS
photoListViewController.person = [person name];
[self.navigationController pushViewController:photoListViewController animated:YES];
[photoListViewController release];
[person release];
}
Please help me understand why the code is breaking there. Appreciate any suggestions.
Person *person = [fetchedResultsController objectAtIndexPath:indexPath];
cell.textLabel.text = person.name; //This works fine
[person release];
[person release]
is the problem - no need to release person if it's not alloc'd there. That causes person
to be over-released, leading to the crash when something else tries to access it.
Even though, in this example, it's ok to manipulate an autoreleased object (due to simplicity of the manipulations, i.e. you are just grabbing one property of *person), the proper way would be to retain your Person object and release it at the end:
Person *person = [[fetchedResultsController objectAtIndexPath:indexPath] retain];
// bla bla
[person release];
精彩评论