I am trying to read and then update a value using Core Data, but when I run it, I get “EXC_BAD_ACCESS”, but when I debug it, it works
I am trying to get the hang of Core Data, and I am running into a strange issue. I have an app that uses a local notification to alert the user, whereupon the user enters my app and this method is called:
- (void)application:(UIApplication *)app didReceiveLocalNotification:(UILocalNotification *)notif {
When the app loads, I prompt another alert view to get some information from the user:
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@" Did you %@?", notif.alertBody] message:@""
delegate:self cancelButtonTitle:@"No..." otherButtonTitles:@"Yes!", nil];
[alert show];
And then every time this alert is shown, I want to increment a counter value in my Core Data DB, and I do that by calling this method right after I show the alert:
[self incrementVal];
Inside of this method, I read a value, turn it into an int, then pass the new number off to another method that will then save the new value in my db.
-(void) incrementVal{
//for reading from the db
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:@"score" inManagedObjectContext:managedObjectContext_];
[fetchRequest setEntity:entity];
NSError *error;
NSPredicate * pred = [NSPredicate predicateWithFormat:@"id == 2"];
[fetchRequest setPredicate:pred];
NSArray * strengthVal = [managedObjectContext_ executeFetchRequest:fetchRequest error:&error];
armorScore * armo = [strengthVal objectAtIndex:0];
int aScor = [armo.score intValue];
aScor++;
//For updating the db
[self updateDBVal:aScor];
[fetchRequest release];
}
开发者_开发知识库 -(void) updateDBVal:(int)value{
NSFetchRequest *fetchRequest2 = [[NSFetchRequest alloc] init];
NSEntityDescription *entity2 = [NSEntityDescription
entityForName:@"score" inManagedObjectContext:managedObjectContext_];
[fetchRequest2 setEntity:entity2];
NSError *error2;
NSPredicate * pred2 = [NSPredicate predicateWithFormat:@"id == 2"];
[fetchRequest2 setPredicate:pred2];
NSArray * banna = [managedObjectContext_ executeFetchRequest:fetchRequest2 error:&error2];
armorScore * bann2 = [banna objectAtIndex:0];
bann2.score = [NSString stringWithFormat:@"%d", value];
[managedObjectContext_ save:&error2];
[error2 release];
[fetchRequest2 release];
}
So I don't know if this approach is ideal, but it is the one that I came up with. It runs fine when I debug it and go through each line, but when I just run it, it crashes saying Exc_Bad_Access...
What am I doing wrong? I really want to get this figured out.
Thanks!!
This is what you're doing wrong:
[error2 release];
精彩评论