Objective-C:接收“EXC_BAD_ACCESS”信号

时间:2012-05-01 20:53:57

标签: objective-c exc-bad-access

  

可能重复:
  EXC_BAD_ACCESS when trying to get iPhone screen dimensions

我在objective-c中有以下代码片段,它自动将一些变量设置为多个预设。但是,在标记的行上,我收到“程序接收信号:EXC_BAD_ACCESS”异常。

令我困惑的是,上面的行是相同的,只是具有不同的值。如果第1行没有抛出异常,为什么第2行呢?我该怎么办?

提前致谢!

星级

- (IBAction)presetPressed:(id)sender {
    if(self.userEnteringNumber) [self enterPressed];

    double xVal;
    double aVal;
    double bVal;
    NSString *preset = [sender currentTitle];
    if ([preset isEqualToString:@"1"]) {
        xVal = 1;
        aVal = 2;
        bVal = 3;
    } else if ([preset isEqualToString:@"2"]) {
        xVal = 1.5;
        aVal = 2.9;
        bVal = 3.0;
    } else if ([preset isEqualToString:@"3"]) {
        xVal = -1;
        aVal = -2;
        bVal = -3;
    }
    [self.variables setValue:[NSNumber numberWithDouble:xVal] forKey:@"x"];
    [self.variables setValue:[NSNumber numberWithDouble:aVal] forKey:@"a"];
    [self.variables setValue:[NSNumber numberWithDouble:bVal] forKey:@"b"];

    self.xVar.text = [NSString stringWithFormat:@"= %@", xVal];
    self.aVar.text = [NSString stringWithFormat:@"= %@", aVal]; //EXC_BAD_ACCESS here
    self.bVar.text = [NSString stringWithFormat:@"= %@", bVal];

    [self calculateResult];
}

2 个答案:

答案 0 :(得分:1)

将格式字符串@"= %@"替换为@"= %g"

您的格式化字符串假设给定的参数值是对象实例(%@)但您提供的标量double值不是对象实例而是基本类型。

答案 1 :(得分:1)

xValaValbVal都是原始双打,但您的字符串格式是通过%@查找对象。

尝试将%@替换为%f(或%g,如果您更喜欢科学记数法):

    self.xVar.text = [NSString stringWithFormat:@"= %f", xVal];
    self.aVar.text = [NSString stringWithFormat:@"= %f", aVal];
    self.bVar.text = [NSString stringWithFormat:@"= %f", bVal];