Search code examples
objective-cxcodensstringnsstringencoding

NSString returning NULL while doing NSUTF8StringEncoding


Following is my code

NSString *res = [valueArray valueForKey:@"key"];
NSData *newdata=[res dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
res=[[NSString alloc] initWithData:newdata encoding:NSNonLossyASCIIStringEncoding];
nameTxt.text = [NSString stringWithFormat:@"%@",res]; // Assigning to textfield

this works properly. But sometimes it returns NULL data, mostly it happens when string contents large data.

Anyone have idea why this is happening?


Solution

  • NSString *res = [valueArray valueForKey:@"key"];
    

    That's funny: using a valueForKey: on a variable named ...Array. Rather seems to be a dictionary?

    NSData *newdata = [res dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
    

    creating a raw UTF8 encoded data from a string always works: No need for allowLossyConversion.

    res = [[NSString alloc] initWithData:newdata encoding:NSNonLossyASCIIStringEncoding];
    

    Converting the UTF8 encoded raw data to ASCII does only work if the UTF8 did not contain any characters out of the very restricted ASCII range. Otherwise nil is returned.

    This seems to be the only reason for this obfuscated bit of code: filter out non-ASCII strings. Otherwise the conversion does not make the slightest sense.