NSData from NSKeyedArchiver to NSString

I am trying to convert NSData generated from NSKeyedArchiver to NSString so that I can pass it and eventually convert back to NSData. I have to pass this as a string (I am using the tr20 url). I went through various encodings, UTF8, ASCII, etc. And I can’t make anything work. NSKeyedArchiver says that NSData is formed as a list of properties: NSPropertyListBinaryFormat_v1_0.

Does anyone know how I can convert these NSData to String and vice versa? Row size is not a problem.

thanks

+6
source share
3 answers

What would you like:

id<nscoding> obj; NSData * data = [NSKeyedArchiver archivedDataWithRootObject:obj]; NSString * string = [data base64EncodedString]; 

And then vice versa

 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 now it is enabled by default

+11
source

iOS 9.2.1, Xcode 7.2.1, ARC enabled

base64EncodedString, dataFromBase64String: depreciates after iOS 7.0

Updated solution:

Encode string:

 id<nscoding> obj; NSData *data = [NSKeyedArchiver archivedDataWithRootObject:obj]; NSString *string = [data base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed]; 

Decode 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 in kSecValueData.

Hope this helps someone! Greetings.

+2
source

All you have to do is something like this:

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

then extract the data:

 NSString *stringFromData = [[NSString alloc] initWithData:dataFromString encoding:NSASCIIStringEncoding]; 
+1
source

Source: https://habr.com/ru/post/888860/


All Articles