@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
然后我做
- (IBAction)startTimers:(id)sender {
timer1 = [[ClassWithTimer alloc] initWithName:@"time1"];
timer2 = [[ClassWithTimer alloc] initWithName:@"time2"];
[timer1 startTimer];
[timer2 startTimer];
[timer1 stopTimer];
[timer2 stopTimer];
}
当我停止计时器时,我看到timer1与timer2相同,而invalidate方法在[timer2 stopTimer]中抛出异常,因为此时此对象无效。
我知道这是iOS政策,但我找不到相关的文档。
答案 0 :(得分:0)
移动
NSTimer *up;
进入接口块内的.h文件。
答案 1 :(得分: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