I have an NSData object with a chunk of binary data and I'm trying to use getBytes:range: to set a primitive.
I can do this:
NSData* data =开发者_如何学Python [...get record from file...]
double value = 0;
[data getBytes:&value range:NSMakeRange(42, 8)];
[someObject setValue:value];
I would rather not have to use a temporary variable as I have many fields in this file I need to read.
Is there an easy way (objc or c) to extract bytes out of an NSData object, cast these bytes to some primitive value, and assign it to an object without using some temporary?
Thanks!
It's not the prettiest, but you can get the raw data pointer used by NSData and dereference it in the proper location.
UInt8 *rawData = [theData bytes];
[someObject setValue:*((double*)(&rawData[42]))];
This involves lots of casting, but you only need to use one temporary variable instead of one for each data type, and it will be slightly faster as you don't repeatedly ask the NSData object for a specific range of data.
精彩评论