iOS NSLog error with Unicode characters

前端 未结 2 1972
滥情空心
滥情空心 2021-01-13 02:09

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

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


        
相关标签:
2条回答
  • 2021-01-13 02:42

    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.

    0 讨论(0)
  • 2021-01-13 02:48

    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.

    0 讨论(0)
提交回复
热议问题