Something strange is going on with my iphone app. I am using Core Data to store data in a SQLite database. The first time after my app starts up I try to read a table to return all of the rows to fill a UITableView with a list of things for the user to select from. If they chos开发者_Go百科e the top item in the list I get a EXC_BAD_ACCESS exception. If they choose any other item everything seems OK. Here is the code sample: Sport and Team are NSManagedObjects. sports is an NSArray of Sport objects fetched using an NSFetchedResultsController (fetchedObjects). I can display the list of objects fine in the UITableView (I use the same array for the cellForRowAtIndexPath() call without any problem
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
Sport *sport = (Sport *)[sports objectAtIndex:indexPath.row];
if (teamSetup) {
if (team.sport != sport) {
[team setSport:sport]; <-- this is where the EXC_BAD_ACCESS happens
NSError *error;
[team.managedObjectContext save:&error];
}
[self.navigationController popViewControllerAnimated:YES];
} else {
// .. do some other stuff
}
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
UPDATE: It seems to only affect the last record in the NSArray instead of the first until it throws the EXC_BAD_ACCESS error. After I restart the app again the problem goes away and the code works as expected :(
There's nothing wrong with the line above whereEXC_BAD_ACCESS
occurs. However, it could offer a clue that there's an issue with either theteam
orsport
objects. The first avenue to pursue is that one of those objects has been deallocated because it has not been retained sufficiently.
Objects that are released may not be deallocated immediately. That's why theEXC_BAD_ACCESS
can occur at weird times. The objects are only deallocated when the chunk of memory that they were using is no longer needed. Other objects would of course use the same chunk. So when that chunk becomes eligible for deallocation is out of your control as the developer. That's handled by the runtime.
Best thing is to first run the Analyzer, then run Instruments, profiling with the Leaks instrument.
There's a great explanation of all this, and point by point advice on tracking downEXC_BAD_ACCESS
errors on Lou Franco's site:
Understanding EXC_BAD_ACCESS
精彩评论