Monday, May 13, 2013

NSString cStringUsingEncoding example ios


cStringUsingEncoding:

Returns a representation of the receiver as a C string using a given encoding.
- (const char *)cStringUsingEncoding:(NSStringEncoding)encoding
Parameters
encoding
The encoding for the returned C string.
Return Value of [NSString cStringUsingEncoding]
A C string representation of the receiver using the encoding specified by encoding. Returns NULL if the receiver cannot be losslessly converted to encoding.
Discussion of [NSString cStringUsingEncoding]
The returned C string is guaranteed to be valid only until either the receiver is freed, or until the current autorelease pool is emptied, whichever occurs first. You should copy the C string or use getCString:maxLength:encoding: if it needs to store the C string beyond this time.[NSString cStringUsingEncoding]
You can use canBeConvertedToEncoding: to check whether a string can be losslessly converted to encoding. If it can’t, you can use dataUsingEncoding:allowLossyConversion: to get a C-string representation using encoding, allowing some loss of information (note that the data returned by dataUsingEncoding:allowLossyConversion: is not a strict C-string since it does not have a NULL terminator).
Example of [NSString cStringUsingEncoding]
NSString *string = @"ü";
const char *c = [string cStringUsingEncoding:NSISOLatin1StringEncoding];
NSString *newString = [[NSString alloc]initWithCString:c encoding:NSUTF8StringEncoding];
NSLog(@"%@",newString); // ü
Example of [NSString cStringUsingEncoding]
NSString* str1 = @"est un rêve en noir";

NSString* str = [NSString stringWithUTF8String:[str1 cStringUsingEncoding:NSUTF8StringEncoding]];
NSLog(@"%@", str);