Saturday, June 1, 2013

NSData getBytes example in Objective C (iOS).

NSData getBytes

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

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

A buffer into which to copy data.
The number of bytes from the start of the receiver's data to copy to buffer.

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

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

Example of [NSData getBytes].
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 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 example article.