Posted By

0xced on 09/26/07


Tagged

utf8 omni invalid nsstring


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

tcol


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. // http://www.omnigroup.com/ftp/pub/software/Source/MacOSX/Frameworks/
  2. // Link with {OWF, OmniFoundation, OmniBase, OmniNetworking}
  3. // http://forums.omnigroup.com/showthread.php?t=1867
  4. #import <OWF/OWDataStream.h>
  5. #import <OWF/OWDataStreamCharacterCursor.h>
  6.  
  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  

You need to login to post a comment.