我正在尝试使用Core Data读取然后更新一个值,但是当我运行它时,我得到“EXC_BAD_ACCESS”,但是当我调试它时,它工作正常

时间:2011-02-21 18:15:39

标签: iphone core-data exc-bad-access

我正试图搞砸Core Data,我遇到了一个奇怪的问题。我有一个使用本地通知提醒用户的应用程序,然后用户输入我的应用程序并调用此方法:

- (void)application:(UIApplication *)app didReceiveLocalNotification:(UILocalNotification *)notif {

当应用加载时,我会提示另一个警报视图以从用户那里获取一些信息:

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@" Did you %@?", notif.alertBody] message:@""
                                                   delegate:self cancelButtonTitle:@"No..." otherButtonTitles:@"Yes!", nil];

    [alert show];

然后每次显示此警报时,我想在我的Core Data DB中增加一个计数器值,我在显示警报后立即调用此方法:

[self incrementVal];

在此方法的内部,我读取一个值,将其转换为int,然后将新数字传递给另一个方法,然后将新值保存在我的数据库中。

-(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];
   }

所以我不知道这种方法是否理想,但这是我提出的方法。当我调试它并遍历每一行时,它运行正常,但是当我运行它时,它崩溃说Exc_Bad_Access ......

我做错了什么?我真的很想弄明白这一点。

谢谢!

1 个答案:

答案 0 :(得分:1)

这就是你做错了:

[error2 release];