Iphone EXC_坏_访问错误,原因不明

Iphone EXC_坏_访问错误,原因不明,iphone,objective-c,memory-management,exc-bad-access,Iphone,Objective C,Memory Management,Exc Bad Access,好的,这是我程序中的一种方法,它不断地给EXC_BAD_访问错误和崩溃。我在下面指出了这一行。questionsShown是一个readwrite属性,它指向一个NSMutableArray,我在程序的前面一个点初始化它的容量为99。调试时,就所分配的属性而言,一切都正常。我认为内存管理一定有问题,但我发现这个问题有很大的困难。提前感谢您的帮助 @synthesize questionList; @synthesize questionLabel; @synthesize questionsSh

好的,这是我程序中的一种方法,它不断地给EXC_BAD_访问错误和崩溃。我在下面指出了这一行。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++;
}
}

EXC_BAD_访问来自解引用
r
,它只是一个整数。编译器应该在这一行给您一个警告(不带强制转换的整数生成指针)

如果questionsShown应该是某种类型的索引集(看起来是这样),您可能希望使用该类,或者必须在NSNumber对象中框选整数。因此:

[questionsShown addObject:[NSNumber numberWithInt:r]];
当你读到它时:

[questionsShown indexOfObjectIdenticalTo:[NSNumber numberWithInt:r]]
不过,我建议您看看

使用可变索引集,您可以执行以下操作:

[questionsShownIndexSet containsIndex:r]


这就解决了问题,我来看看NSIndexSet。非常感谢,我还有很多客观的c语言需要探索。
[questionsShownIndexSet addIndex:r]