Saturday, June 1, 2013

NSData getBytes range example in Objective C (iOS).


NSData getBytes range

Copies a range of bytes from the receiver’s data into a given buffer.

- (void)getBytes:(void *)buffer range:(NSRange)range

Parameters of [NSData getBytes range]
buffer
A buffer into which to copy data.
range
The range of bytes in the receiver's data to copy to buffer. The range must lie within the range of bytes of the receiver's data.

Discussion of [NSData getBytes range]
If range isn’t within the receiver’s range of bytes, an NSRangeException is raised.

NSData getBytes range example.
NSData *data = ...;
NSMutableArray *bytes = [NSMutableArray array];
for (NSUInteger i = 0; i < [data length]; i++) {
    unsigned char byte;
    [data getBytes:&byte range:NSMakeRange(i, 1)];
    [bytes addObject:[NSString stringWithFormat:@"%x", byte]];
}
NSLog(@"%@", bytes);

Example of [NSData getBytes range].
- (NSData *)getSubData:(NSData *)source withRange:(NSRange)range
{
    UInt8 bytes[range.length];
    [source getBytes:&bytes range:range];
    NSData *result = [[NSData alloc] initWithBytes:bytes length:sizeof(bytes)];
    return [result autorelease];
}

NSData getBytes range example.
UInt16 anUInt16;
float aFloat;

int position = 0;

[data getBytes:&anUInt16 range:NSMakeRange(position, sizeof(UInt16))];
position += sizeof(UInt16);

[data getBytes:&aFloat range:NSMakeRange(position, sizeof(float))];
position += sizeof(float);

End of NSData getBytes range example article.