2

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?

Reno Jones
  • 1,979
  • 1
  • 18
  • 30
  • Xcode returns `NULL`? How does it do that? And what is this code supposed to do other than a seemingly pointless conversion from string -> data -> string? – trojanfoe Feb 26 '13 at 10:15
  • 1
    in Textfield it shows (null) value sometimes, i don't know why. if you know then let me know @trojanfoe. – Nikhil Thakkar Feb 26 '13 at 10:20
  • And what happens if you do `nameTxt.text = [valueArray valueForKey:@"key"];`? – trojanfoe Feb 26 '13 at 10:22
  • whether u hitting any service with this code? – Ganapathy Feb 26 '13 at 10:24
  • 1
    it show me data with unicodes, but for converting unicodes to Emoji i am using this code. @trojanfoe – Nikhil Thakkar Feb 26 '13 at 10:26
  • when i send to server i used this code NSData *data = [nameTxt.text dataUsingEncoding:NSNonLossyASCIIStringEncoding]; NSString *str =[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; [req setPostValue:str forKey:@"key"]; – Nikhil Thakkar Feb 26 '13 at 10:32

1 Answers1

2
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.

Nikolai Ruhe
  • 81,520
  • 17
  • 180
  • 200
  • More likely: Code copied from somewhere without any understanding. – gnasher729 Mar 11 '16 at 10:34
  • And just by coincidence I found a post where someone did that nonsense with the express purpose of handling Emojis correctly somehow. Which is of course totally pointless. – gnasher729 Mar 11 '16 at 10:37