Sunday, May 12, 2013

NSString canBeConvertedToEncoding example ios


canBeConvertedToEncoding:

Returns a Boolean value that indicates whether the receiver can be converted to a given encoding without loss of information.
- (BOOL)canBeConvertedToEncoding:(NSStringEncoding)encoding
Parameters
encoding
A string encoding.
Return Value of [NSString canBeConvertedToEncoding]
YES if the receiver can be converted to encoding without loss of information. Returns NO if characters would have to be changed or deleted in the process of changing encodings.
Discussion of [NSString canBeConvertedToEncoding]
If you plan to actually convert a string, the dataUsingEncoding:... methods return nil on failure, so you can avoid the overhead of invoking this method yourself by simply trying to convert the string.
Example of [NSString canBeConvertedToEncoding]
if ([myString canBeConvertedToEncoding:NSASCIIStringEncoding]) {
    const char *asciiString = [myString cStringUsingEncoding:NSASCIIStringEncoding];
}
Example of [NSString canBeConvertedToEncoding]
if ([string canBeConvertedToEncoding:NSUnicodeStringEncoding]) {
    NSData * data = [string dataUsingEncoding:NSUnicodeStringEncoding];
    const unichar* const ptr = (const unichar*)data.bytes;
    ...
}
Example of [NSString canBeConvertedToEncoding]
// Define Block variable to tests out different encodings
void (^tryGetCStringUsingEncoding)(NSString*, NSStringEncoding) = ^(NSString* originalNSString, NSStringEncoding encoding) {
    NSLog(@"Trying to convert \"%@\" using encoding: 0x%X", originalNSString, encoding);
    BOOL canEncode = [originalNSString canBeConvertedToEncoding:encoding];
    if (!canEncode)
    {
        NSLog(@"    Can not encode \"%@\" using encoding %X", originalNSString, encoding);
    }
    else
    {
        // Try encoding using NSString getCString:maxLength:encoding:
        NSUInteger cStrLength = [originalNSString lengthOfBytesUsingEncoding:encoding];
        char cstr[cStrLength];
        [originalNSString getCString:cstr maxLength:cStrLength encoding:encoding];
        NSLog(@"    Converted(1): \"%s\"  (expected length: %u)",
              cstr, cStrLength);

        // Try encoding using NSString dataUsingEncoding:allowLossyConversion:          
        NSData *strData = [originalNSString dataUsingEncoding:encoding allowLossyConversion:YES];
        char cstr2[[strData length] + 1];
        memcpy(cstr2, [strData bytes], [strData length] + 1);
        cstr2[[strData length]] = '\0';
        NSLog(@"    Converted(2): \"%s\"  (expected length: %u)",
              cstr2, [strData length]);
    }
};