2011-04-19 66 views
0
@interface ClassWithTimer : NSObject { 

} 
-(void) startTimer; 
-(void) stopTimer; 
@end 

@implementation ClassWithTimer 

NSTimer *up; 

-(void) startTimer{ 
    up = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(doSomething) userInfo:nil repeats:YES]; 

-(void) stopTimer{ 
    [up invalidate]; 
} 

- (void) doSomething{} 
@end 

然後我做到一個內存地址IOS設置相同,但不同的對象

- (IBAction)startTimers:(id)sender { 
    timer1 = [[ClassWithTimer alloc] initWithName:@"time1"]; 
    timer2 = [[ClassWithTimer alloc] initWithName:@"time2"]; 

    [timer1 startTimer]; 
    [timer2 startTimer];  

    [timer1 stopTimer]; 
    [timer2 stopTimer]; 
} 

當我停止計時器我看到TIMER1同爲Timer2和在無效的方法拋出異常[定時器2 stopTimer]因爲這個對象此時失效。

我知道這是iOS政策,但我找不到這方面的文檔。

回答

0

移動

NSTimer *up; 

到接口塊內的.h文件中。

0

NSTimer需要是一個iVar,你只是在類中自由聲明,允許兩個類共享相同的計時器。你也需要釋放前一個定時器,然後在startTimer中保留新定時器。

@interface ClassWithTimer : NSObject { 
    NSTimer *up; //Declare iVar(instance variables) here 
} 
-(void) startTimer; 
-(void) stopTimer; 
@end 

@implementation ClassWithTimer 

-(void) startTimer{ 
    [up invalidate]; 
    [up release]; 
    up = [[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(doSomething) userInfo:nil repeats:YES] retain]; 

-(void) stopTimer{ 
    [up invalidate]; //Do these same this line 
    [up release]; //and this line in your dealloc 
    up = nil; 
} 

- (void) doSomething{} 
@end 
相關問題