假设我有一个包含32位int值的二进制文件(使用Java生成)。我目前正在使用以下Objective-C代码进行解析:

NSString *path = [[NSBundle mainBundle] pathForResource:@"foo" ofType:@"dat"];
NSFileHandle *file = [NSFileHandle fileHandleForReadingAtPath:path];

unsigned long intValue;
memcpy(&intValue, [[file readDataOfLength:4] bytes], 4);
intValue = NSSwapBigLongToHost(intValue);

[file closeFile];

我的第一个问题是询问这是否是在iPhone上做事的常用方式,因为我没有找到任何接近Java的DataInputStream的东西。

我的第二个问题与memcpy的代码行有关。我不明白为什么以下部分(更优雅,更少“低级别”)不起作用:

[[file readDataOfLength:4] getbytes:&intValue];

我在构建时收到警告:

'NSData' may not respond to '-getbytes:'

执行时,我得到了:

'NSInvalidArgumentException', reason: '*** -[NSConcreteData getbytes:]: unrecognized selector sent to instance
有帮助吗?

解决方案

对于最后一个问题,请使用getBytes(大写B)。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top