2009-06-22 69 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