问题描述
我有一个包含一些条件的方法.第一个条件可以正常工作,并且不会引起任何问题.但是,第二个会导致应用崩溃.
I have a method that contains a few conditionals. The first conditional works fine and does not cause any problems. However, the second one causes the app to crash.
- (void)didReceiveGaiaGattResponse:(CSRGaiaGattCommand *)command
{
GaiaCommandType cmdType = [command getCommandId];
NSData *requestPayload = [command getPayload];
uint8_t success = 0;
NSLog(@"cmdType: %li", (long)cmdType);
[requestPayload getBytes:&success range:NSMakeRange(0, sizeof(uint8_t))];
if (cmdType == GaiaCommand_GetCurrentBatteryLevel && requestPayload.length > 1)
{
uint16_t value = 0;
[requestPayload getBytes:&value range:NSMakeRange(1, sizeof(uint16_t))];
NSInteger battery = CFSwapInt16BigToHost(value);
[self sendEventWithName:someDEVICE_BATTERY_CHANGED body:@{@"batteryLevel":[NSNumber numberWithInteger:battery]}];
return;
}
else if (cmdType == GaiaCommand_GET_FBC && requestPayload.length > 1)
{
uint16_t value = 0;
[requestPayload getBytes:&value range:NSMakeRange(1, sizeof(uint16_t))];
NSInteger feedbackCancellationMode = CFSwapInt16BigToHost(value);
[self sendEventWithName:FEEDBACK_CANCELLATION_MODE body:@{@"feedbackCancellationMode": [NSNumber numberWithInt:feedbackCancellationMode]}];
return;
}
//do more stuff
}
有条件的
没有问题.
但是,有条件的
在xcode中引起以下警告
causes the following warning in xcode
此外,我还在调试器中看到了错误消息
In addition, I also saw the error message in the debugger
数据长度2'
推荐答案
考虑一下这是在告诉你什么:
Consider what this is telling you:
Terminating app due to uncaught exception 'NSRangeException', reason:
'-[_NSInlineData getBytes:range:]: range {1, 2} exceeds data length 2'
您的数据对象的长度为2个字节.根据您的代码,位置0处的第一个字节是success
值.这样在位置1还有一个字节要处理.但是您的代码尝试从其中复制2个字节-消息中的range {1, 2}
;从位置1开始,长度为2的范围.您正在读取数据的末尾.
Your data object is 2 bytes in length. The first byte, at position 0, is (according to your code) the success
value. That leaves one more byte at position 1 to handle. But your code is attempt to copy 2 bytes out of it — that's the range {1, 2}
in the message; a range starting at position 1 and with a length of 2. You're reading past the end of the data.
您必须检查数据是否有足够的数据可以满足您尝试进行的-getBytes:...
调用.您可能还需要更正关于缓冲区中取消模式值应该有多大的假设,因为它显然比您期望的要小.您的代码假定它是一个uint16_t
(2个字节),但是数据中只剩下一个字节.
You have to check that the data has enough data to satisfy the -getBytes:...
call you're attempting to make. You may also need to correct your assumptions about how large the cancellation mode value in the buffer is supposed to be, because it's apparently smaller than you expect. Your code assumes it's a uint16_t
(2 bytes) but there's only one byte left in the data.
这篇关于为什么此条件导致错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!