【问题标题】:EXC_BAD_ACCESS Error for no conceivable reasonEXC_BAD_ACCESS 莫名其妙的错误
【发布时间】:2010-07-02 03:00:57
【问题描述】:

好的,这是我程序中的一种方法,它不断给出 EXC_BAD_ACCESS 错误并崩溃。我指出了下面的行。 questionsShown 是一个读写属性,它指向一个 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++;
}
}

【问题讨论】:

    标签: iphone objective-c memory-management exc-bad-access


    【解决方案1】:

    EXC_BAD_ACCESS 来自取消引用r,它只是一个整数。您的编译器应该在该行上给您一个警告(从整数生成指针而不进行强制转换)。

    如果 questionsShown 应该是为您设置的某种索引(看起来确实如此),您可能想要使用该类,或者您必须将整数装箱到 NSNumber 对象中。所以:

    [questionsShown addObject:[NSNumber numberWithInt:r]];
    

    当你阅读它时:

    [questionsShown indexOfObjectIdenticalTo:[NSNumber numberWithInt:r]]
    

    不过,我建议您查看NSIndexSet documentation

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

    [questionsShownIndexSet containsIndex:r]
    

    [questionsShownIndexSet addIndex:r]
    

    【讨论】:

    • 解决了它,并且看不到 NSIndexSet。非常感谢,我还有很多目标 C 语言要探索。
    猜你喜欢
    • 2019-02-04
    • 1970-01-01
    • 2012-05-19
    • 1970-01-01
    • 1970-01-01
    • 2012-03-12
    • 2013-04-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多