2009-06-22 6 views
2

I는 다음과 같습니다 몇 가지 코드가 있습니다액세스 NSArray를

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 액션 안에 배열! 아마 뭔가를 놓친 적이 있습니까?

답변

8

arrayWithObjects:는 오토 릴리즈 객체를 반환하고, 당신이 그것을 유지하지 않을 때문에 그것은 당신의 타이머 화재 전에 실행 루프의 끝에서 해제되고 있습니다. 그것을 유지하거나 동등한 alloc/init 메소드를 사용하고, 작업이 끝나면 그것을 놓기를 원할 것이다. 먼저 메모리 관리에 대해 읽으십시오. 여러분이 잘 이해할 때까지는 이런 종류의 문제에 부딪 히게 될 것입니다.

0

배열과 actualColor 변수를 타이머 메서드에서 사용할 수 있도록 클래스의 인스턴스 변수로 만들어야합니다. 그것은 다음과 같이 보일 것입니다 :

@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

이것이 왜 투표되지 않았는지 전혀 알 수 없습니다. 아이디어에 감사드립니다! – cregox