Friday, May 3, 2013

NSKeyedUnarchiver decodeBytesForKey example ios

decodeBytesForKey :returnedLength:

Decodes a stream of bytes associated with a given key.
- (const uint8_t *)decodeBytesForKey:(NSString *)key returnedLength:(NSUInteger *)lengthp
Parameters of [NSKeyedUnarchiver decodeBytesForKey]
A key in the archive within the current decoding scope. key must not be nil.
Upon return, contains the number of bytes returned.
Return Value
The stream of bytes associated with the key key. Returns NULL if key does not exist.
Discussion of [NSKeyedUnarchiver decodeBytesForKey]
The returned value is a pointer to a temporary buffer owned by the receiver. The buffer goes away with the unarchiver, not the containing autoreleasepool block. You must copy the bytes into your own buffer if you need the data to persist beyond the life of the receiver.
Example of [NSKeyedUnarchiver decodeBytesForKey]
NSUInteger len = (unsigned int)(rows * columns * sizeof(float));
float * temp = (float * )[coder decodeBytesForKey:@"matrix" returnedLength:&len];
Example of [NSKeyedUnarchiver decodeBytesForKey]
typedef struct
    NSInteger x;
    NSInteger y;

- (void) testDecoding
    NSString* myKey = @"Testing";

    // First get an coder with bytes in it
    NSMutableData* myData = [[NSMutableData data] retain];
    NSKeyedArchiver* myCoder = [[NSKeyedArchiver alloc] initForWritingWithMutableData:myData];

    BBPointI32 encodedStruct = {1234, 5678};
    [myCoder encodeBytes:(const uint8_t *)&encodedStruct length:sizeof(encodedStruct) forKey:myKey];
    [myCoder finishEncoding];

    // Now decode it
    BBPointI32 decodedStruct;
    NSUInteger decodedLength = 0;
    NSKeyedUnarchiver* myDecoder = [[NSKeyedUnarchiver alloc] initForReadingWithData:myData];
    uint8_t* data = (uint8_t*)[myDecoder decodeBytesForKey:myKey returnedLength:&decodedLength];
    decodedStruct = *(BBPointI32*)data;
    NSLog(@"Got decoded struct with x = %ld, y = %ld, length = %lu", decodedStruct.x, decodedStruct.y, decodedLength);

- (void)applicationDidFinishLaunching:(UIApplication *)application {    
    NSLog(@"Testing decoding");
    [self testDecoding];