Question

Say I have a binary file (generated with Java) containing a 32 bit int value. I'm currently using the following Objective-C code for parsing it:

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];

My first question is to ask if it's the common way of doing things on the iPhone because I didn't find anything close to Java's DataInputStream.

My second question is related to the line of code with a memcpy. I don't undestand why the following part (more elegant, less "low-level") is not working instead:

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

I'm getting a warning on build:

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

On execution, I'm getting:

'NSInvalidArgumentException', reason: '*** -[NSConcreteData getbytes:]: unrecognized selector sent to instance
Was it helpful?

Solution

For the last question, use getBytes (uppercase B).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top