Pergunta

I have two NSData objects I want to store within a third NSData object. The idea is I want to make it easy when I later decode the larger object, to get at the two smaller objects independently of one another, without worrying about their relative sizes or datatypes.

It appears the best way to do this is to use NSKeyedArchiver to create a sort of root-level key-value structure within the larger NSData object, in which I can store the two smaller objects within separate keys. That's what I've attempted to do here:

NSData *data1Before = [@"abcdefgh" dataUsingEncoding:NSUTF8StringEncoding];
NSData *data2Before = [@"ijklmnop" dataUsingEncoding:NSUTF8StringEncoding];

NSMutableData *allData = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:allData];
[archiver encodeObject:data1Before forKey:@"key1"];
[archiver encodeObject:data2Before forKey:@"key2"];
[archiver finishEncoding];

NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:allData];
NSData *data1After = [unarchiver decodeObjectForKey:@"key1"];
NSData *data2After = [unarchiver decodeObjectForKey:@"key2"];
[unarchiver finishDecoding];

NSString *string1After = [NSString stringWithUTF8String:[data1After bytes]];
NSString *string2After = [NSString stringWithUTF8String:[data2After bytes]];

NSLog(@"after1: %@",string1After);
NSLog(@"after2: %@",string2After);

The problem is, when you run this code over and over, you get all sorts of different results coming from the NSLog statements- someetimes special characters get appended to the end of the strings, sometimes they're just NULL.

It appears this corruption has something to do with this "double-encoding" process I'm using. When I modify the code so that the NSKeyedArchiver just calls encodeObject directly on NSStrings, rather than on NSData objects, I can later use decodeObjectForKey and get at those strings without any problems- no corruption at all.

Is there a better way of doing this than using NSKeyedArchiver? Or am I using it incorrectly?

Foi útil?

Solução

Thanks to rmaddy for his answer above- I just needed to replace this:

[NSString stringWithUTF8String:[data1After bytes]];

with this:

[[NSString alloc] initWithData:data1After encoding: NSUTF8StringEncoding];

and that fixed it.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top