首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从NSTimer间隔访问NSArray = EXC_BAD_ACCESS

从NSTimer间隔访问NSArray = EXC_BAD_ACCESS
EN

Stack Overflow用户
提问于 2009-06-22 14:52:04
回答 2查看 1.4K关注 0票数 2

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

代码语言:javascript
复制
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];

在选择器中,我有以下内容:

代码语言:javascript
复制
- (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操作中访问我的数组!我是不是错过了什么?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2009-06-22 15:16:42

arrayWithObjects:返回一个自动释放的对象,因为您没有保留它,所以在计时器触发之前,它将在run循环结束时被释放。您希望保留它或使用等效的alloc/init方法,并在使用完它后释放它。不过,请务必先阅读有关内存管理的内容,在您对它有一个很好的理解之前,您将会遇到各种各样的问题。

票数 8
EN

Stack Overflow用户

发布于 2009-06-22 15:14:26

您必须将targetColors数组和actualColor变量转换为类的实例变量,以便在timer方法中使用它们。它看起来像这样:

代码语言:javascript
复制
@interface YourClass : NSObject
{
    //...
    int actualColor;
    NSArray * targetColors;
}
@end

@implementation YourClass

- (id)init
{
    if ((self = [super init]) == nil) { return nil; }

    //...
    actualColor = 0;
    targetColors = [[NSArray arrayWithObjects:[UIColor blueColor],
                                              [UIColor purpleColor],
                                              [UIColor greenColor],
                                              [UIColor brownColor],
                                              [UIColor cyanColor],
                                             nil] retain];
    return self;
}

- (void)dealloc
{
    [targetColors release];
    //...
    [super dealloc];
}

//...

@end
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1027658

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档