Posted By

0xced on 09/26/07


utf8 omni invalid nsstring

Versions (?)

Who likes this?

1 person have marked this snippet as a favorite


Handle invalid UTF-8

 / Published in: Objective C

Convert UTF-8 NSData to NSString without failing if UTF-8 is invalid. Instead, replace invalid characters with the replacement character (�). This requires some Omni frameworks. Use this as a replacement for NSString's initWithData:encoding: method.

  1. //
  2. // Link with {OWF, OmniFoundation, OmniBase, OmniNetworking}
  3. //
  4. #import <OWF/OWDataStream.h>
  5. #import <OWF/OWDataStreamCharacterCursor.h>
  7. NSString* stringWithUTF8Data(NSData *data)
  8. {
  9. OWDataStream *dataStream = [[[OWDataStream alloc] initWithLength:[data length]] autorelease];
  10. [dataStream writeData:data];
  11. return OFMostlyApplyDeferredEncoding([[[[OWDataStreamCharacterCursor alloc] initForDataCursor:[dataStream newCursor] encoding:OFDeferredASCIISupersetStringEncoding] autorelease] readString], kCFStringEncodingUTF8);
  12. }

Report this snippet  


RSS Icon Subscribe to comments
Posted By: sxcaskjc on April 21, 2018 Thanks for sharing.I found a lot of interesting information here. A really good post, very thankful and hopeful that you will write many more posts like this one.

Posted By: barryflash2727 on September 21, 2018

You need to login to post a comment.