Reputation: 8609
I have an NSData abject called objNSData, and I can convert a string into this NSData object. I cannot figure out how to convert an NSData back to a string, is that even possible? I know it can be done in Visual Basic with a command such as
Data.ToString
Is there something like this in Objective-C?
Upvotes: 0
Views: 1416
Reputation: 39296
NSData just contains raw bytes. You need an encoding to go back and forth. With just raw bytes, it's not useful unless you know how to encode them. For example, in this snippet, we convert a string to bytes, and then back to a string using a UTF8 encoding (character set).
NSString *foo = @"BarBaz";
NSData *data = [foo dataUsingEncoding:NSUTF8StringEncoding];
NSString *fooString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"string=%@", fooString);
This outputs:
2011-10-11 20:41:20.708 Craplet[3413:707] string=BarBaz
Upvotes: 2
Reputation: 47729
Well, ya gotta kinda know what the data is. If it's graphic data it isn't going to make a very pretty string.
But I assume that what you have is character data of some sort. Is it ASCII? UTF8? UTF16? Klingon?
If it's UTF8, you'd use something like
NSString* theString = [NSString stringWithUTF8String:[yourDataObject bytes]];
But there are lots of variables, such as is the data null terminated?
Upvotes: 1