2009-06-22 70 views
2

我有一些代碼,看起來像這樣:訪問的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

您必須將targetColors數組和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 2011-01-13 22:08:12