从NSTimer Interval = EXC_BAD_ACCESS访问NSArray

baD*_*aDa 2 iphone cocoa objective-c

我有一些看起来像这样的代码:

actualColor = 0;
targetColors = [NSArray arrayWithObjects:[UIColor blueColor],
                                         [UIColor purpleColor],
                                         [UIColor greenColor],
                                         [UIColor brownColor],
                                         [UIColor cyanColor], nil];
timer = [NSTimer scheduledTimerWithTimeInterval:3.0
                                         target:self
                                       selector:@selector(switchScreen)
                                       userInfo:nil
                                        repeats:YES];
Run Code Online (Sandbox Code Playgroud)

在选择器中我有这个:

- (void) switchScreen
{
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.5];
    [UIView setAnimationDelegate:self];

    int totalItens = [targetColors count];
    NSLog(@"Total Colors: %i",totalItens);
    if(actualColor >= [targetColors count])
    {
        actualColor = 0;
    }

    UIColor *targetColor = [targetColors objectAtIndex:actualColor];

    if(!firstUsed)
    {
        [firstView setBackgroundColor:targetColor];
        [secondView setAlpha:0.0];
        [firstView setAlpha:1.0];
        firstUsed = YES;
    }
    else 
    {
        [firstView setBackgroundColor:targetColor];
        [secondView setAlpha:1.0];
        [firstView setAlpha:0.0];
        firstUsed = NO;
    }
    [UIView commitAnimations];

    actualColor++;        
}
Run Code Online (Sandbox Code Playgroud)

但似乎我无法在scheduledTimer Action中访问我的数组!我可能错过了什么吗?

Mar*_*eau 8

arrayWithObjects:返回一个自动释放的对象,因为你没有保留它,它会在你的计时器触发之前在运行循环结束时被释放.您希望保留它或使用等效的alloc/init方法,并在完成后释放它.一定要先阅读有关内存管理的内容,但是在你对它有一个很好的理解之前,你会遇到各种各样的问题.