I have an NSData object.
I want to convert it to a string, go to a function, and then go back to the NSData object.
But how?
I tried this method, but NSData is different from the original!
here is 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 source NSData?
data and dataNM vary in size. The compiler returns 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] * Termination of the application to exclude the exception "NSInvalidArgumentException", reason: '- [__ NSCFData objectForKey:]: unrecognized selector sent to instance 0x6b46c80
thanks.
source share