9

I'm trying to convert NSData generated from NSKeyedArchiver to an NSString so that I can pass it around and eventually convert it back to NSData. I have to pass this as a string (I'm using three20 URL passing). I've gone through various encodings, UTF8, ASCII, etc. and can't get anything to work. NSKeyedArchiver says that the NSData is formated as a property list: NSPropertyListBinaryFormat_v1_0.

Does anyone have any idea how I can convert this NSData to a String and back again? Size of the string isn't an issue.

Thanks

kodai
  • 3,080
  • 5
  • 32
  • 34

3 Answers3

14

What you want is:

id<nscoding> obj;

NSData * data     = [NSKeyedArchiver archivedDataWithRootObject:obj];
NSString * string = [data base64EncodedString];

And then the other way around

NSString * string;

NSData * data    = [NSData dataFromBase64String:string];
id<nscoding> obj = [NSKeyedUnarchiver unarchiveObjectWithData:data]

You can add base64EncodedString and dataFromBase64String: with the NSData category available here NSData+Base64 but it is now included by default

Nicolas Manzini
  • 8,379
  • 6
  • 63
  • 81
2

iOS 9.2.1, Xcode 7.2.1, ARC enabled

base64EncodedString, dataFromBase64String: depreciated after iOS 7.0

Updated solution:

Encode to string:

id<nscoding> obj;

NSData *data     = [NSKeyedArchiver archivedDataWithRootObject:obj];
NSString *string = [data base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];

Decode to data:

NSString *string;

NSData *data    = [[NSData alloc] initWithBase64EncodedString:string options:(NSDataBase64DecodingIgnoreUnknownCharacters)];
id<nscoding> obj = [NSKeyedUnarchiver unarchiveObjectWithData:data];

Note: This is very useful when working with keychain to store a dictionary of key/value pairs into kSecValueData.

Hope this helps someone! Cheers.

serge-k
  • 3,394
  • 2
  • 24
  • 55
0

All you should have to do is something like this:

NSData *dataFromString = [[NSString stringWithFormat:@"%@", yourString] dataUsingEncoding:NSASCIIStringEncoding];

then to extract the data:

NSString *stringFromData = [[NSString alloc] initWithData:dataFromString encoding:NSASCIIStringEncoding];
justin
  • 5,811
  • 3
  • 29
  • 32
  • Unfortunatly, and I'm not sure why, this doesn't seem to work. I get a very short string, for example "bplist00Ô" as my output. – kodai May 23 '11 at 22:28
  • That's definitely odd. I'm going to test a couple things as alternatives and get back to you with (hopefully) something that does work – justin May 23 '11 at 22:30
  • What I posted did the trick for me, though I noticed that if you decode the data into a string from a different method than when you encode it, you get faults. This can be fixed by adding `retain` to the `dataFromString` instance after you encode your string. Hopefully this fixes the issue you were having. If not, there is another possible route to take if necessary – justin May 23 '11 at 22:44