我有一个可以移动的生成的子视图。每次移动我都检查它是否在X轴上通过了300。我的问题是,当它通过该点并且你没有停止移动它时,NSTimer经常启动,程序崩溃。
NSArray *subviews = [self.view subviews];
for (UIView *subview in subviews) {
if (subview.frame.origin.x > 300) {
NSMutableArray *data = [[NSMutableArray alloc] initWithCapacity:1];
[data addObject:subview];
[NSTimer scheduledTimerWithTimeInterval:3.00 target:self selector:@selector(callFunction:) userInfo:data repeats:NO];
}
}
答案 0 :(得分:1)
您应该保留对NSTimer
个实例的引用,当您不再希望它被解雇时,您可以致电-[NSTimer invalidate]
更新此外,您是否打算在循环中安排计时器?
答案 1 :(得分:0)
添加一个属性,用于保存对计时器的引用。因此,您始终可以检查NSTimer是否已经启动,并通过
停止 [NSTimer invalidate];
您添加了一个属性@property(nonatomic, strong) NSTimer *timer
,然后您可以检查:
if(!self.timer){
self.timer = [NSTimer scheduledTimerWithTimeInterval:3.00 target:self selector:@selector(callFunction:) userInfo:data repeats:NO];
}
答案 2 :(得分:-1)
试试这个:
[NSTimer invalidate];
NSTimer = nil;