我正在处理 garmin GDL90 协议(protocol),它以二进制形式将各种类型的消息发送到我的 IOS 设备。我正在尝试处理所有这些消息,但遇到了问题。具体来说,消息是按字节打包的,因此如果您看到
0x7d 0x5e
或 0x7d 0x5d
您必须将它们转换为 0x7d 或 0x7e
我已经设置了我的代码,以便检测我正在解析的消息类型,然后调用一个函数:
- (void) parseMessage:(NSMutableData *)message
做我的数据解析。我的各个消息解析函数调用父函数 [super parseMessage:message];
,它处理公共(public)元素的解析以及处理我的字节填充。这些函数调用中的每一个都需要一个 NSData *
,所以在我的 super 函数中所做的修改不应该返回相同的数据吗?
我应该使用引用传递还是什么?有什么建议吗?
我的函数有两个变体 - unstuff1 抛出错误,unstuff2 不起作用。
- (NSMutableData *)unstuff1:(NSMutableData *)mutableData {
int dataLength = [mutableData length];
char *bytes = [mutableData bytes];
// Scan bytes ignoring 1st and last byte because they will be 7e's
for (int i = dataLength - 1; i > 0; i--) {
bytes[i + 1] ^= 0x20;
if (i + 1 == dataLength) {
NSLog(@"Terminal character padding detected on character %d with length %d", i, dataLength);
} else {
/* Replace 2 bytes with a single byte should remove the flag when you do this */
[mutableData replaceBytesInRange:NSMakeRange(i, 2) withBytes:&bytes[i + 1] length:1];
dataLength--;
}
}
return mutableData;
}
- (NSMutableData *)unstuff2:(NSMutableData *)data {
NSMutableData *mutableData = [[NSMutableData alloc] initWithData:data];
int dataLength = [mutableData length];
char *bytes = [mutableData bytes];
// Scan bytes ignoring 1st and last byte because they will be 7e's
for (int i = dataLength - 1; i > 0; i--) {
bytes[i + 1] ^= 0x20;
if (i + 1 == dataLength) {
NSLog(@"Terminal character padding detected on character %d with length %d", i, dataLength);
} else {
/* Replace 2 bytes with a single byte should remove the flag when you do this */
[mutableData replaceBytesInRange:NSMakeRange(i, 2) withBytes:&bytes[i + 1] length:1];
dataLength--;
}
}
return mutableData;
}
在 unstuff2 中,显然我正在制作一个新的 MutableData,所以我猜这会导致内存地址更改(这是我使用的函数,它给了我指定的错误)。
unstuff1 抛出以下异常:
-[_NSInlineData replaceBytesInRange:withBytes:length:]: unrecognized selector sent to instance 0x178250d40
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[_NSInlineData replaceBytesInRange:withBytes:length:]: unrecognized selector sent to instance
最佳答案
与 C++ 和 C#(仅举两个例子)等语言不同,Objective C 没有“通过引用传递”的概念。但是,将指针的副本传递给 NSMutableData 在功能上等同于通过引用传递对象。也就是说,如果您将 NSMutableData(或 NSMutableAnything)传递给一个函数并且该函数对其进行了修改,则调用函数将看到它传递的对象中反射(reflect)的更改。
https://stackoverflow.com/questions/22389518/
相关文章:
makefile - 了解 kbuild 构建过程的工作原理
authentication - oAuth 2.0 - 代表用户行事
sql - 有没有办法删除已经绑定(bind)到存储过程的用户定义表类型?
wpf - 在不破坏 ControlTemplate 的情况下将 setter 添加到 Contro
google-chrome-extension - 我可以在我的网站上有一个 chrome 扩展的安
django - @login_required 和 is_authenticated() -- 在