سؤال

What is wrong with this method?

- (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 is an integer declared using the following, int count = 0;. I get an EXC_BAD_ACCESS error on line number 3. I believe it happens on the second time through the method because if I comment out [self randomInteger]; no error message is thrown.

هل كانت مفيدة؟

المحلول

it may used too much stack space because recursion.

try this

- (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;
        }
    }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top