iphone - 从 NSTimer 访问 NSArray 间隔 = EXC_BAD_ACCESS

标签 iphone objective-c cocoa

我有一些代码,如下所示:

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];

在选择器中我有这个:

- (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++;        
}

但我似乎无法在 ScheduledTimer Action 中访问我的数组!我是不是错过了什么?

最佳答案

arrayWithObjects: 返回一个自动释放的对象,由于您没有保留它,因此它会在运行循环结束时、计时器触发之前被释放。您想要保留它或使用等效的 alloc/init 方法,并在完成后释放它。不过,请务必先阅读有关内存管理的内容,在充分理解它之前,您将遇到诸如此类的各种问题。

关于iphone - 从 NSTimer 访问 NSArray 间隔 = EXC_BAD_ACCESS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1027658/

相关文章:

ios - Iphone 应用程序不会每次都请求许可

ios - 如何在iPhone 6/6s Plus上保持人像启动屏幕

iphone - 如何确定应用程序首次安装或使用的日期?

ios - 连接到 Wi-Fi 网络时,获取其所有接入点

objective-c - 在并发队列中使用dispatch_semaphore_t发生死锁

iphone - 如何在 pickerview 上添加完成按钮?

iphone - 配置文件过期

iphone - 通过通知执行选择器OnMainThread

macos - 如何在 OS X 上将低级转义序列发送到打印机?

macos - beginSheet 方法对我不起作用