iOS:使用 NSTimer 写入蓝牙 LE 设备

iOS: Writing to Bluetooth LE device with NSTimer

我正在尝试向我的蓝牙 LE 设备写入一个字符,到目前为止它已经成功,但只有当我在 didDiscoverCharacteristicsForService 方法中执行它时。

- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error {
    if (error) {
        [self cleanup];
        return;
    }

    for (CBCharacteristic *characteristic in service.characteristics) {
        if ([characteristic.UUID isEqual: CHAR_UUID]) {
            NSLog(@"Discovered characteristic: %@", characteristic);
            [peripheral setNotifyValue:YES forCharacteristic:characteristic];
            _discoveredCharacteristic = characteristic;

            char c;
            count++;
            if (count%2 == 1)
            {
                c = 0x0;
            }
            else
            {
                c = 0x7;
            }

            NSData *data = [NSData dataWithBytes: &c length: 1];
            [_discoveredPeripheral writeValue:data forCharacteristic:_discoveredCharacteristic
                                         type:CBCharacteristicWriteWithResponse];

            NSLog(@"Writing value %@ for characteristic %@", data, _discoveredCharacteristic.UUID);
        }
    }

timer = [NSTimer scheduledTimerWithTimeInterval:2
                                                 target:self selector:@selector(targetMethod:)
                                               userInfo:nil repeats:YES];
        _repeatingTimer = timer;
    }

但是当我将 writeValue 部分移动到一个由计时器触发的方法中时, 它不再将值写入我的设备。为什么是这样?我做错了什么?

- (void)targetMethod:(NSTimer*)theTimer{
    char c;
    count++;
    if (count%2 == 1)
    {
        c = 0x0;
    }
    else
    {
        c = 0x7;
    }

    NSData *data = [NSData dataWithBytes: &c length: 1];
    [_discoveredPeripheral writeValue:data forCharacteristic:_discoveredCharacteristic
                                 type:CBCharacteristicWriteWithResponse];

    NSLog(@"Writing value %@ for characteristic %@", data, _discoveredCharacteristic.UUID);
}

我对 iOS 和蓝牙都很陌生。

我傻了,写完就关闭外设