首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Objective-C 燈光閃爍定時器實現:1 秒間隔閃爍的正確代碼模式

     編輯:程式設計綜合問答

常見錯誤模式

// ❌ 錯誤:在循環中 sleep 阻塞主線程
while (flashing) {
    light.on = !light.on;
    [NSThread sleepForTimeInterval:1.0];  // 界面凍結、無法響應事件
}

正確方案:NSTimer / CADisplayLink

方案一:NSTimer (傳統)

@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;
}

方案二:GCD 定時源 (現代、精準)

@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;
}

關鍵要點

  • 主線程更新 UI:所有視圖操作必須在主隊列
  • 非阻塞:定時器回調異步執行,不阻塞主線程
  • 生命周期管理:dealloc / viewDidDisappear 中必須取消定時器
  • 弱引用 self:GCD block 中使用 __weak typeof(self) weakSelf = self; 避免循環引用

硬件控制擴展

- (void)toggleLight {
    lightOn = !lightOn;
    // 假設通過串口/藍牙發送指令
    [self sendCommand:lightOn ? @"LIGHT_ON" : @"LIGHT_OFF"];
}

參考資源

百度文檔:定時器計數方式實現閃爍

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved