I’m trying to learn objective-c. I’m trying to parse a binary file doing the following (simplified):
@interface DatFile : NSObject {
NSData* _data;
}
-(id)initWithFilePath:(NSString *)filePath;
-(void) readFile;
-(void) auxiliaryMethod;
@implementation DatFile
- (id) initWithFilePath:(NSString *)filePath {
if ( self = [super init] ) {
_data = [NSData dataWithContentsOfFile:filePath];
}
return self;
}
-(void) readFile {
int header;
[_data getBytes: &header range: NSMakeRange(0, 4)];
NSLog(@"header: %u", header);
short key;
[_data getBytes: &key range: NSMakeRange(4, 2)];
NSLog(@"key: %u", key);
short value;
[_data getBytes: &value range: NSMakeRange(6, 1)];
NSLog(@"value: %u", value);
[self auxiliaryMethod];
}
-(void) auxiliaryMethod {
short value;
[_data getBytes: &value range: NSMakeRange(6, 1)];
NSLog(@"value: %u", value);
}
My problem is that the code inside the auxiliaryMethod does not compute the same value computed by readFile method. Since the _data object is the same, why the method are computing different values? And, as you can see, the logic inside the auxiliaryMethod is just a copy of the other one…
In other languages (java) I usually separate some logic in smaller methods in order to make the code mode readable/maintainable. This is why I’m trying to mimic it with ObjC.
Of course that probably missing something, but after some hours, I gave up. I don’t see where is my mistake. Probably I should erase my project and start it again…
TIA,
Bob
%uis for printing a 32 bit unsigned value. A short is 16 bits. Therefore, you are printing the parsed value plus some stack garbage.Try
%hu; thehmodifies%uto print a short value.If that doesn’t work:
(don’t see how they can’t be… but…)
With this kind of bug, it is pretty much guaranteed it is either that you aren’t dealing with the input you think you are or you are dealing with some C-ism related to data types and the implied conversions in this kind of code.
I.e. assuming
_datais consistent, then it indicates that the code you think is working is not actually working, but only appearing to by coincidence.