// ❌ 錯誤:在循環中 sleep 阻塞主線程
while (flashing) {
light.on = !light.on;
[NSThread sleepForTimeInterval:1.0]; // 界面凍結、無法響應事件
}
@property (nonatomic, strong) NSTimer *flashTimer;
@property (nonatomic, assign) BOOL lightOn;
- (void)startFlashing {
lightOn = NO;
flashTimer = [NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:@selector(toggleLight)
userInfo:nil
repeats:YES];
}
- (void)toggleLight {
lightOn = !lightOn;
self.lightView.backgroundColor = lightOn ? [UIColor yellowColor] : [UIColor blackColor];
// 或調用硬件控制接口
}
- (void)stopFlashing {
[flashTimer invalidate];
flashTimer = nil;
}
@property (nonatomic, strong) dispatch_source_t flashTimer;
- (void)startFlashing {
lightOn = NO;
flashTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());
dispatch_source_set_timer(flashTimer,
dispatch_walltime(NULL, 0), // 立即開始
1.0 * NSEC_PER_SEC, // 1 秒間隔
0.1 * NSEC_PER_SEC); // 容差 100ms
dispatch_source_set_event_handler(flashTimer, ^{
lightOn = !lightOn;
dispatch_async(dispatch_get_main_queue(), ^{
self.lightView.backgroundColor = lightOn ? [UIColor yellowColor] : [UIColor blackColor];
});
});
dispatch_resume(flashTimer);
}
- (void)stopFlashing {
dispatch_source_cancel(flashTimer);
flashTimer = nil;
}
dealloc / viewDidDisappear 中必須取消定時器__weak typeof(self) weakSelf = self; 避免循環引用- (void)toggleLight {
lightOn = !lightOn;
// 假設通過串口/藍牙發送指令
[self sendCommand:lightOn ? @"LIGHT_ON" : @"LIGHT_OFF"];
}
百度文檔:定時器計數方式實現閃爍