default C String Encoding
default C String Encoding
- Subject: default C String Encoding
- From: Julien Jalon <email@hidden>
- Date: Wed, 7 Nov 2001 05:33:52 +0100
While discussing (via mail) with the author of Adium, I went on a
problem with cString methods of NSString:
1) according to the NSString doc, you can't change the default C String
encoding (you can get it with [NSString defaultCStringEncoding] but not
set it) :/
Maybe we can do something? I think it's usefull to change the default C
string encoding (since MacOS Roman is not the most used encoding with
terminal/internet exchange applications... look at all those instant
messenger program like Adium which don't use the right encoding :( )
2) there is no NSString method to convert from and to C string using
other encodings than the default one (Mac OS Roman) and UTF8 encoding. I
don't understand why Apple does not provide those facilities.
Here is my workaround for 2) with the ISOLatin1 Encoding but you can
easily do a more general one and/or complete it with the other NSString
cString method:
@interface NSString (ISOLatin1Additions)
+ (NSString *)stringWithISOLatin1EncodedCString:(const char *)cString;
- (const char *)ISOLatin1EncodedCString;
@end
@implementation NSString (ISOLatin1Additions)
+ stringWithISOLatin1EncodedCString:(const char *)cString {
return [[[NSString alloc] initWith
Data:[NSData dataWithBytes:cString
length:strlen(cString)] encoding:NSISOLatin1StringEncoding] autorelease];
}
- (const char *)ISOLatin1EncodedCString {
char *returnValue;
NSData *encodedData=[self
dataUsingEncoding:NSISOLatin1StringEncoding allowLossyConversion:YES];
unsigned dataLength=[encodedData length];
returnValue=malloc(dataLength+1);
strncpy(returnValue,(char *)[encodedData bytes],dataLength);
// trick to "autorelease" returnValue...
// I think that's the method used by Apple for the
// "autoreleased" result of -cString (see NSString doc)
[NSData dataWithBytesNoCopy:returnValue length:dataLength+1];
return returnValue;
}
@end
--Julien