2013-07-30 88 views
1

我正在使用CoreBluetooth框架,在我更新了特性值後,我從外設獲取回調didUpdateValueForCharacteristic。在這裏,我發現了一個片段都在NSData對象中解碼返回的數據:NSData的範圍錯誤

- (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); 
} 

下面的代碼拋出一個異常:

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

有人能解釋一下爲什麼?我應該讀取的值應該是1個字節。

+0

你在哪裏發送subdataWithRange:消息?你描述的錯誤與你顯示的代碼無關。 – Sven

+0

我試過你的代碼,什麼都沒有發生。它看起來像一個「索引超出」的錯誤,你可以發佈更多的代碼? – hago

+0

@hago,我發現這發生在別處,並且與這段代碼沒有任何關係。我將在實際發生的地方更新我的代碼。 – chwi

回答

1

當您在characteristic上致電subdataWithRange:NSMakeRange(1, length)時,您所要求的數據不存在。在嘗試從中提取數據之前,您應該檢查characteristic的長度。你還應該檢查你的邏輯,以確定你認爲characteristic中應該有多少數據,因爲這看起來是無效的。

+0

爲什麼我看到的是 「NSUInteger *標誌=(NSUInteger *)[[[特性值] subdataWithRange:NSMakeRange(0,1)]字節];」,作者已更新? – hago

+0

@hago,問題已更新,是的 – Wain