EXC_BAD_ACCESS错误,无可能的原因

wfb*_*ale 3 iphone memory-management exc-bad-access objective-c

好的,这是我的程序中的一个方法,它一直给出EXC_BAD_ACCESS错误并崩溃.我在下面说明了这一行.questionsShown是一个readwrite属性,指向一个NSMutableArray,我在程序的早期点初始化容量为99.当我调试时,就所分配的属性而言,所有内容都显得正常.我认为内存管理一定存在问题,但我在查找问题时遇到了严重问题.在此先感谢您的帮助.

@synthesize questionList;
@synthesize questionLabel;
@synthesize questionsShown;

-(IBAction)next{
int numElements = [questionList count];
int r;
if (myCount == numElements){
    [questionLabel setText:@"You have seen all the questions, click next again to continue anyways."];
    [questionsShown release];
    questionsShown = [[NSMutableArray alloc] initWithCapacity:99];
    myCount = 0;
}
else {
    do {
        r = rand() % numElements;
    } while ([questionsShown indexOfObjectIdenticalTo:r] != NSNotFound);
    NSString *myString = [questionList objectAtIndex:(NSUInteger)r];
    [questionLabel setText:myString];
    myCount++;
    [questionsShown addObject:r]; //results in crash with message EXC_BAD_ACCESS
    myCount++;
}
}
Run Code Online (Sandbox Code Playgroud)

Jas*_*oco 10

EXC_BAD_ACCESS来自解除引用r,它只是一个整数.你的编译器应该给你一个警告(在没有强制转换的情况下从整数生成指针).

如果questionShown应该是某种类型的索引(它看起来像是),你可能想要使用该类,或者你必须在NSNumber对象中打包整数.所以:

[questionsShown addObject:[NSNumber numberWithInt:r]];
Run Code Online (Sandbox Code Playgroud)

当你读它:

[questionsShown indexOfObjectIdenticalTo:[NSNumber numberWithInt:r]]
Run Code Online (Sandbox Code Playgroud)

但是,我建议您查看NSIndexSet文档.

使用可变索引集,您可以:

[questionsShownIndexSet containsIndex:r]
Run Code Online (Sandbox Code Playgroud)

[questionsShownIndexSet addIndex:r]
Run Code Online (Sandbox Code Playgroud)