How to use printf with NSString
You can convert an NSString
into a UTF8
string by calling the UTF8String
method:
printf("%s", [string UTF8String]);
//public method that accepts a string argument
- (void) sayThis : ( NSString* ) this
{
printf("%s",[this cString]);
}
According to the NSString.h ( html version ) the UTF8String method is only available on Mac OSX.
(see below ) All the other methods I looked at are marked as 'availability:Openstep'
There are further methods that will return regular char* strings but they might throw character conversion exceptions.
NOTE The string pointers point to memory that might go away so you have to copy the strings if you want to keep a copy of the string contents, but immediate printing should be fine ?
There are also methods that will return an encoded string, and a method to test if the encoding you want will work ( I think ) so you can check if your required encoding will work and then request a string that has been encoded as required.
From reading through the .h file itself there are many encodings and translations between encodings. These are managed using enumerations so you can pass the type of encoding you want as an argument.
On linux etc. do :
locate NSString.h ** Note this found the html doc file also
otherwise do a :
find /usr -name NSString.h
NOTE Your mileage may vary :)
Thanks.
From the NSString.h html doc file :
cString - (const char*) cString; Availability: OpenStep
Returns a pointer to a null terminated string of 8-bit characters in the default encoding. The memory pointed to is not owned by the caller, so the caller must copy its contents to keep it. Raises an NSCharacterConversionException if loss of information would occur during conversion. (See -canBeConvertedToEncoding: .)
cStringLength - (NSUInteger) cStringLength; Availability: OpenStep
Returns length of a version of this unicode string converted to bytes using the default C string encoding. If the conversion would result in information loss, the results are unpredictable. Check -canBeConvertedToEncoding: first.
cStringUsingEncoding: - (const char*) cStringUsingEncoding: (NSStringEncoding)encoding; Availability: MacOS-X 10.4.0, Base 1.2.0
Returns a pointer to a null terminated string of characters in the specified encoding. NB. under GNUstep you can used this to obtain a nul terminated utf-16 string (sixteen bit characters) as well as eight bit strings. The memory pointed to is not owned by the caller, so the caller must copy its contents to keep it. Raises an NSCharacterConversionException if loss of information would occur during conversion.
canBeConvertedToEncoding: - (BOOL) canBeConvertedToEncoding: (NSStringEncoding)encoding; Availability: OpenStep
Returns whether this string can be converted to the given string encoding without information loss.