EXC_BAD_ACCESS StringWithFormat

时间:2014-04-22 00:02:13

标签: ios objective-c exc-bad-access

这种方法有什么问题?

- (void)randomInteger {
    count = (arc4random() % 5000) + 5000;
    NSString *countString = [NSString stringWithFormat:@"%i", count];
    if([countString rangeOfString:@"0"].location != NSNotFound && [countString rangeOfString:@"1"].location != NSNotFound && [countString rangeOfString:@"2"].location != NSNotFound && [countString rangeOfString:@"3"].location != NSNotFound) {
        score.text = [NSString stringWithFormat:@"%i", count];
    } else {
        [self randomInteger];
    }
}

count是使用以下int count = 0;声明的整数。我在第3行得到一个EXC_BAD_ACCESS错误。我相信它会在第二次通过该方法发生,因为如果我注释掉[self randomInteger];,则不会抛出任何错误消息。

1 个答案:

答案 0 :(得分:3)

它可能会使用太多的堆栈空间,因为递归。

试试这个

- (void)randomInteger {
    while (true) {
        int count = arc4random_uniform(5000) + 5000;
        NSString *countString = [NSString stringWithFormat:@"%i", count];
        if([countString rangeOfString:@"0"].location != NSNotFound && 
            [countString rangeOfString:@"1"].location != NSNotFound &&
             [countString rangeOfString:@"2"].location != NSNotFound &&
              [countString rangeOfString:@"3"].location != NSNotFound) {
            score.text = countString;
            break;
        }
    }
}