Convert UTF-8 encoded NSData to NSString

前端 未结 7 793
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-22 08:43

I have UTF-8 encoded NSData from windows server and I want to convert it to NSString for iPhone. Since data contains characters (like a degree symb

7条回答
  •  隐瞒了意图╮
    2020-11-22 08:46

    Just to summarize, here's a complete answer, that worked for me.

    My problem was that when I used

    [NSString stringWithUTF8String:(char *)data.bytes];
    

    The string I got was unpredictable: Around 70% it did contain the expected value, but too often it resulted with Null or even worse: garbaged at the end of the string.

    After some digging I switched to

    [[NSString alloc] initWithBytes:(char *)data.bytes length:data.length encoding:NSUTF8StringEncoding];
    

    And got the expected result every time.

提交回复
热议问题