1

I am using the CoreBluetooth framework, where after I have updated a value for a characteristic I get the callback didUpdateValueForCharacteristic from the peripheral. Here, I found a snippet do decode the data within the NSData object returned:

- (void) peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{

    NSUInteger *flags = (NSUInteger*) [[[characteristic value] subdataWithRange:NSMakeRange(0, 1)] bytes];
    NSUInteger length;
    if(*flags & 0x01)
    {
        length = 2;
    }
    else
    {
        length = 1;
    }
    NSUInteger *measurement = (NSUInteger*) [[[characteristic value] subdataWithRange:NSMakeRange(1, length)] bytes];

    NSLog(@"Value read from char: %d", *measurement);
}

Here the code throws an exception:

*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[NSConcreteData subdataWithRange:]: range {1, 1} exceeds data length 1'

Could someone explain why? The value I am supposed to read should be 1 byte.

4

1 回答 1

1

当您调用subdataWithRange:NSMakeRange(1, length)时,characteristic您要求的是不存在的数据。characteristic在尝试从中提取数据之前,您应该检查它的长度。您还应该检查您的逻辑,以了解您如何决定应该包含多少数据,characteristic因为这似乎是无效的。

于 2013-07-30T09:11:23.733 回答