Convert UTF-8 encoded NSData to NSString

前端 未结 7 918
佛祖请我去吃肉
佛祖请我去吃肉 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:57

    I humbly submit a category to make this less annoying:

    @interface NSData (EasyUTF8)
    
    // Safely decode the bytes into a UTF8 string
    - (NSString *)asUTF8String;
    
    @end
    

    and

    @implementation NSData (EasyUTF8)
    
    - (NSString *)asUTF8String {
        return [[NSString alloc] initWithData:self encoding:NSUTF8StringEncoding];    
    }
    
    @end
    

    (Note that if you're not using ARC you'll need an autorelease there.)

    Now instead of the appallingly verbose:

    NSData *data = ...
    [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    

    You can do:

    NSData *data = ...
    [data asUTF8String];
    

提交回复
热议问题