Saturday, June 1, 2013

NSData getBytes length example in Objective C (iOS).


NSData getBytes length

Copies a number of bytes from the start of the receiver's data into a given buffer.

- (void)getBytes:(void *)buffer length:(NSUInteger)length

Parameters of [NSData getBytes length]
buffer
A buffer into which to copy data.
length
The number of bytes from the start of the receiver's data to copy to buffer.

Discussion of [NSData getBytes length]
The number of bytes copied is the smaller of the length parameter and the length of the data encapsulated in the object.

NSData getBytes length example.
NSData *imageData = UIImagePNGRepresentation(recipeImage.image); 
NSUInteger len = [imageData length];
Byte *byteData= (Byte*)malloc(len);
[imageData  getBytes:byteData length:len];

Example of [NSData getBytes length].
NSData *info = [torrent valueForKey:@"info"];
NSData *name = [info valueForKey:@"name"];
unsigned char aBuffer[[name length]];
[name getBytes:aBuffer length:[name length]];
NSLog(@"File name: %s", aBuffer);
..which retrives the data, but seems to have additional unicode rubbish after it:

File name: ubuntu-8.10-desktop-i386.iso)

NSData getBytes length example.
you'll probably be able to use something along the following lines to convert into a usable numeric format using getBytes:length: on your NSData object. For e.g.

NSUInteger unencodedInteger;
[myDataObject getBytes:&unencodedInteger length:sizeof(unencodedInteger)];

End of NSData getBytes length example article.