Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass NSData as NSString and get it back?

i have a NSData object.

I want to convert it to a string, pass to a function and then reconvert back to NSData object.

But How?

I tried this method, but NSData value it's different from the original!

here my code:

  // a generic class
  APClass *c = [[APClass alloc] init];
  c.aNumber = 123;
  c.aString = @"my string";

  // my data obj
  NSMutableData *data = [NSMutableData data];

  // archiver to store class in nsdata
  NSKeyedArchiver *encoder = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
  [encoder encodeObject:[NSNumber numberWithInt:c.aNumber] forKey:@"aNum"];
  [encoder encodeObject:c.aString forKey:@"aStr"];
  [encoder finishEncoding];
  [encoder release];

  [c release];

  NSLog(@"%@", data);
  NSString *d = [NSString stringWithFormat:@"%@", data];

  // ---

  NSString *strFromData = [NSString stringWithFormat:@"%@", d];

  NSData *dataNM = [strFromData dataUsingEncoding:NSUTF8StringEncoding];

  // decoder to retrieve class from nsdata      
  NSKeyedUnarchiver *decoder = [[NSKeyedUnarchiver alloc] initForReadingWithData:dataNM];
  int number       = [[decoder decodeObjectForKey:@"aNum"] intValue];
  NSString *string = [decoder decodeObjectForKey:@"aStr"];
  [decoder finishDecoding];
  [decoder release];

  NSLog(@"[Number: %d] -- [String: %@]", number, string);

How can i convert back to original NSData?

data and dataNM are different in size. Compiler give back this error:

2012-04-02 16:33:28.269 DataTest[18008:f803] -[__NSCFData objectForKey:]: unrecognized selector sent to instance 0x6b46c80

2012-04-02 16:33:28.270 DataTest[18008:f803] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFData objectForKey:]: unrecognized selector sent to instance 0x6b46c80'

thanks.

like image 444
elp Avatar asked Apr 02 '12 13:04

elp


1 Answers

Solved.

Using dataUsingEncoding, value of NSData it's different.

To pass data around methods or apps, etc, i've used base64 convertion.

Encode

NSString *d = 
  [NSString stringWithFormat:@"appdue://obj=%@", 
     [APBase64Converter base64forData:data]];

Decode

NSData *data = [APBase64Converter base64DataFromString:urlParams];

APBase64Converter Is a lib that encode/decode easily data and strings.

Working example and APBase64Converter lib can be downloaded from here: http://goo.gl/8YNjS

Thanks all.

I "retain" this post for helps people and me next time!

like image 118
elp Avatar answered Oct 06 '22 01:10

elp