我有一个关于我上一篇文章的问题
但我认为首先我应该提供一些代码:
这是处理我创建的对象的函数
- (void)handleObject:(NSMutableData *)object {
NSLog(@"[object length] = %d", [object length]);
Byte *byteArray;
byteArray = (Byte *)[object bytes];
switch (byteArray[5]) {
case 0: NSLog(@"Login OK");
break;
case 1: NSLog(@"Exit. Server disconnect");
break;
case 2: NSLog(@"Ping erhalten");
break;
case 4: NSLog(@"Points received");
break;
case 6: NSLog(@"transfer of POLYLINE vector objects");
break;
case 8: NSLog(@"transfer of POLYGON vector objects");
break;
case 9: NSLog(@"transfer of Render Rule");
break;
case 10: {
NSLog(@"end of response for RequestVectorObjects");
isLoading = FALSE;
}
break;
case 11: NSLog(@"Background Colorcode: %d", (byteArray[6] & 0xFF));
break;
default: NSLog(@"From server: default value");
break;
}
}
我在这里接收来自流的数据
- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode {
switch(eventCode) {
case NSStreamEventHasBytesAvailable:
{
isLoading = YES;
while (isLoading) {
uint8_t bufSize[4];
int packetLength = 0;
[(NSInputStream *)stream read:bufSize maxLength:4];
packetLength = [self bytesToInt:bufSize withOffset:0];
NSLog(@"packetLength: %d", packetLength);
[tempStore appendBytes:bufSize length:4];
if (packetLength == 25600) {
loggedIn = YES;
uint8_t buf[4];
[(NSInputStream *)stream read:buf maxLength:4];
[tempStore appendBytes:buf length:4];
[self handleObject:tempStore];
}
else {
uint8_t buf[packetLength];
[(NSInputStream *)stream read:buf maxLength:packetLength];
[tempStore appendBytes:buf length:packetLength];
[self handleObject:tempStore];
}
[tempStore resetBytesInRange:NSMakeRange(0, [tempStore length])];
[tempStore setLength:0];
}
NSLog(@"Finished loading objects");
} break;
}
这一切都适用于模拟器,或者如果我在 iPhone 上调试应用程序,但如果尝试在设备上运行它,我总是得到 BAD_EXCESS,因为 packetLength 的值是错误的,所以我尝试将太多字节读入我的缓冲。
现在我的问题是:为什么所有值在调试模式下都是正确的,但在运行模式下却完全搞砸了?有什么我可以避免这个问题或我应该注意的吗?
非常感谢您的帮助
这是我的 BytesToInt 函数,但如果接收到的值正确,我认为它可以正常工作
- (int)bytesToInt:(Byte *)b withOffset:(int)offset {
int ret = 0;
for (int i = 0; i < 4; i++) {
ret |= (b[offset + i] & 0xFF) << (3-i)*8;
}
return ret;
}