Доступ к NSArray из NSTimer Interval = EXC_BAD_ACCESS - PullRequest
2 голосов
/ 22 июня 2009

У меня есть код, который выглядит следующим образом:

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

Но, похоже, я не могу получить доступ к своему массиву внутри запланированного действия! Возможно, я что-то пропустил?

Ответы [ 2 ]

8 голосов
/ 22 июня 2009

arrayWithObjects: возвращает автоматически освобожденный объект, и, поскольку вы не сохраняете его, он освобождается в конце цикла выполнения, прежде чем сработает ваш таймер. Вы хотите сохранить его или использовать эквивалентный метод alloc / init и освободить его, когда закончите с ним. Обязательно прочитайте сначала об управлении памятью, но вы будете сталкиваться с такими проблемами, пока не разберетесь в этом.

0 голосов
/ 22 июня 2009

Вам придется преобразовать массив targetColors и переменную actualColor в переменные экземпляра для вашего класса, чтобы их можно было использовать в методе timer. Это будет выглядеть примерно так:

@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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...