ChatGPT解决这个技术问题 Extra ChatGPT

Converting NSData to NSString in Objective c

I want to convert NSData to NSString..What is the best way to do this?

I am using this code but the final string returns null

NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@",str);

When I see console It will print null.

@Nik.... @Marvin: Are you the same person or from within the same lan? I just wonder, why your identicons are exactly the same.
What's the string? If you're getting nil then I guess your data isn't a valid utf8 string?
@vikingosegundo For your kind information i don't know nik...
that is really funny, as it is extremely unlikely. but still possible.

J
Jhaliya - Praveen Sharma

Use below code.

NSString* myString;
myString = [[NSString alloc] initWithData:nsdata encoding:NSASCIIStringEncoding];

this will not give me the proper string
if not, it is not NSASCIIStringEncoding. see felipes answer for other encodings
For this encoding NSUTF8StringEncoding giving nil
C
Cœur

The docs for NSString says

https://developer.apple.com/documentation/foundation/nsstring/1416374-initwithdata

Return Value An NSString object initialized by converting the bytes in data into Unicode characters using encoding. The returned object may be different from the original receiver. Returns nil if the initialization fails for some reason (for example if data does not represent valid data for encoding).

You should try other encoding to check if it solves your problem

 // The following constants are provided by NSString as possible string encodings.
enum {
   NSASCIIStringEncoding = 1,
   NSNEXTSTEPStringEncoding = 2,
   NSJapaneseEUCStringEncoding = 3,
   NSUTF8StringEncoding = 4,
   NSISOLatin1StringEncoding = 5,
   NSSymbolStringEncoding = 6,
   NSNonLossyASCIIStringEncoding = 7,
   NSShiftJISStringEncoding = 8,
   NSISOLatin2StringEncoding = 9,
   NSUnicodeStringEncoding = 10,
   NSWindowsCP1251StringEncoding = 11,
   NSWindowsCP1252StringEncoding = 12,
   NSWindowsCP1253StringEncoding = 13,
   NSWindowsCP1254StringEncoding = 14,
   NSWindowsCP1250StringEncoding = 15,
   NSISO2022JPStringEncoding = 21,
   NSMacOSRomanStringEncoding = 30,
   NSUTF16StringEncoding = NSUnicodeStringEncoding,
   NSUTF16BigEndianStringEncoding = 0x90000100,
   NSUTF16LittleEndianStringEncoding = 0x94000100,
   NSUTF32StringEncoding = 0x8c000100,
   NSUTF32BigEndianStringEncoding = 0x98000100,
   NSUTF32LittleEndianStringEncoding = 0x9c000100,
   NSProprietaryStringEncoding = 65536
};

NSASCIIStringEncoding
I used the numbers in lldb. Otherwise it didn't work. Thanks.
Note: If you are unsure of your encoding type or if it isn't always the same, this approach will be good for you: stackoverflow.com/a/50691430/2057171
M
Morten Fast

-[NSString initWithData:encoding] will return nil if the specified encoding doesn't match the data's encoding.

Make sure your data is encoded in UTF-8 (or change NSUTF8StringEncoding to whatever encoding that's appropriate for the data).


I converted an image into the NSdata and again converting the NSdata into the String using the NSUTF8StringEncoding. But it is showing nil.
N
Nag Raj
NSString *string = [NSString stringWithUTF8String:[Data bytes]];

This does not work as described [[NSString alloc] initWithData:head encoding:NSUTF8StringEncoding] works
A
Alexander Volkov

Objective C:

[[NSString alloc] initWithData:nsdata encoding:NSASCIIStringEncoding];

Swift:

let str = String(data: data, encoding: .ascii)

D
DD_

-[NSString initWithData:encoding] is your friend but only when you use a proper encoding.


J
Jess

Swift:

let jsonString = String(data: jsonData, encoding: .ascii)

or .utf8 or whatever encoding appropriate


C
Community

Unsure of data's encoding type? No problem!

Without need to know potential encoding types, in which wrong encoding types will give you nil/null, this should cover all your bases:

NSString *dataString = [data base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithCarriageReturn];

Done!

Note: In the event this somehow fails, you can unpack your NSData with NSKeyedUnarchiver , then repack the (id)unpacked again via NSKeyedArchiver, and that NSData form should be base64 encodeable.

id unpacked = [NSKeyedUnarchiver unarchiveObjectWithData:data];
data = [NSKeyedArchiver archivedDataWithRootObject:unpacked];

A
Andrew Rondeau

Objective C includes a built-in way to detect a the encoding of a string embedded in NSData.

NSData* data = // Assign your NSData object...

NSString* string;
NSStringEncoding encoding = [NSString stringEncodingForData:data encodingOptions:nil convertedString:&string usedLossyConversion:nil];

A
Ashok R

in objective C:

NSData *tmpData;
NSString *tmpString = [NSString stringWithFormat:@"%@", tmpData];
NSLog(tmpString)

this one is wrong, it will return something like {length = XX, bytes = 0xYYYYYYYY} and I assume question was how to unwrap encoded string from raw bytes, not their description