从NSTimer Interval = EXC_BAD_ACCESS访问NSArray [英] Access NSArray from a NSTimer Interval = EXC_BAD_ACCESS
问题描述
我有一些代码看起来像这样:
I have some code that looks like this:
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中访问我的数组!
But it seems that I cannot access my array inside the scheduledTimer Action! Have I perhaps missed something?
推荐答案
arrayWithObjects:
返回一个自动释放的对象,并且因为你不保留它在运行循环结束时被释放,在你的定时器触发之前。你要保留它或使用等效的alloc / init方法,并在你完成它后释放它。一定要先阅读内存管理,但是你会碰到这样的各种问题,直到你对它有很好的了解。
arrayWithObjects:
returns an autoreleased object, and since you're not retaining it it's being deallocated at the end of the run loop, before your timer fires. You want to either retain it or use the equivalent alloc/init method, and release it when you're done with it. Be sure to read about memory management first though, you're going to run into all kinds of problems like this until you have a good understanding of it.
这篇关于从NSTimer Interval = EXC_BAD_ACCESS访问NSArray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!