2008-12-31 65 views
1

说我有一个二进制文件(用Java生成)包含一个32位的int值。我目前使用下面的Objective-C代码用于解析它:在Cocoa Touch中解析二进制文件的最简单方法是什么?

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 

回答

2

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

相关问题