iOS NSLog error with Unicode characters

假如想象 提交于 2020-01-21 07:20:28

问题


Can anyone tell me the cause of the discrepancy for the following results ?

completionHandler:^(NSArray *placemarks, NSError *error) {
    NSLog(@"\n placemarks%@", placemarks);

Resulting:

placemarks(
"\U039b\U03b5\U03c9\U03c6\U03cc\U03c1\U03bf\U03c2 \U039a\U03cd\U03c0\U03c1\U03bf\U03c5 163, 16451 \U0391\U03c1\U03b3\U03c5\U03c1\U03bf\U03cd\U03c0\U03bf\U03bb\U03b7\U03c2, \U0395\U03bb\U03bb\U03ac\U03c2 @ <+37.90085408,+23.75654648> +/- 100.00m, region (identifier <+37.90085408,+23.75654648> radius 141.62) <+37.90085408,+23.75654648> radius 141.62m"
)

and

for(id object in placemarks ) {NSLog(@"%@ \n", object);}

Resulting

2012-09-14 13:08:23.493 ΑΦΜ[1390:c07] Λεωφόρος Κύπρου 163, 16451 Αργυρούπολης, Ελλάς @ <+37.90085408,+23.75654648> +/- 100.00m, region (identifier <+37.90085408,+23.75654648> radius 141.62) <+37.90085408,+23.75654648> radius 141.62m 

Thank you


回答1:


Interesting :)

Passing %@ into NSLog's format string just means 'call description on an object'.

It looks like description on NSArray deals with unicode characters differently than the description on each object.

However, I suspect that the description method on NSArray just calls description on each of the objects it contains and then, for some reason I'm not 100% sure about, is encoding them before dumping them out to NSLog.




回答2:


Passing %@ to NSLog does call the [NSArray description] on the array. NSArray class reference says that [NSArray description] "returns a string that represents the contents of the array, formatted as a property list". Doing so converts unicode characters to NSNonLossyASCIIStringEncoding. Your NSArray will print correctly if you reverse the process.

completionHandler:^(NSArray *placemarks, NSError *error) {
       NSLog(@"%@", [NSString stringWithCString:[[placemarks description] cStringUsingEncoding:NSASCIIStringEncoding] encoding:NSNonLossyASCIIStringEncoding]);

This works by converting the original string with all of the \Uxxxx encoded universal characters into a c string, then decoding the c string to an NSString reversing the NSNonLossyASCIIStringEncoding which had been done by the [NSLog description]. I have not figured out a way to do this without first converting to a c string.



来源:https://stackoverflow.com/questions/12422599/ios-nslog-error-with-unicode-characters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!