views:

620

answers:

1

I'm having a little dilemma with an iphone project.

I'm getting some JSON data from a webservice. I can deserialize it into a dictionary OK. One of the dictionary values is a binary (a picture), but my JSON library deserializes it as an NSArray of NSDecimalNumbers!

How do I convert this NSArray of NSDecimalNumbers to an NSData object, so that I can successfully generate an image from it, by using [UIImage imageWithData:myNSData]?

+2  A: 

How about this

unsigned char *buffer = (unsigned char*)malloc([arrayOfNumbers count]);
int i=0;
for (NSDecimalNumber *num in arrayOfNumbers) {
    buffer[i++] = [num intValue];
}
NSData *data = [NSData dataWithBytes:buffer length:[arrayOfNumbers count]];
free(buffer);

...or something similar depending the values ranges of the NSDecimalNumbers.

epatel
You could reduce memory consumption and a buffer copy by using `[NSMutableData dataWithLength:[arrayOfNumbers count]];` to allocate the buffer instead of malloc.
Nikolai Ruhe
Brilliant, worked like a charm! =] Been a while since I did raw C, so I guess my syntax was off.