NSData from NSKeyedArchiver to NSString

前端 未结 3 1067
悲&欢浪女
悲&欢浪女 2021-02-08 20:20

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 strin

3条回答
  •  旧时难觅i
    2021-02-08 21:12

    iOS 9.2.1, Xcode 7.2.1, ARC enabled

    base64EncodedString, dataFromBase64String: depreciated after iOS 7.0

    Updated solution:

    Encode to string:

    id 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 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.

提交回复
热议问题