We Recommend

Programming in Objective-C Programming in Objective-C
Programming in Objective-C is a concise, carefully written tutorial on the basics of Objective-C and object-oriented programming. The book makes no assumption about prior experience with object-oriented programming languages or with the C language (upon which Objective-C is based). And because of this, both novice and experienced programmers alike can use this book to quickly and effectively learn the fundamentals of Objective-C.


Posted By

0xced on 09/26/07


Tagged

utf8 omni invalid nsstring


Versions (?)


Who likes this?

1 person has 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.