iOS:在具有特殊字符编码的标签中显示NSStrings的NSArray

时间:2013-06-12 15:16:25

标签: ios objective-c character-encoding

我添加了几个NSStrings NSArray。该字符串可能包含特殊字符。最后,我想将数组打印到UILabel

非常简化的代码(如果您认为我错过了某些内容,请与我联系):

NSString *strBuffer = @"Röckdöts";
NSLog(@"String: %@", strBuffer);

NSMutableArray *marrSelectedStrings = [[NSMutableArray alloc] init];
[marrSelectedStrings addObject:strBuffer];
NSLog(@"Array: %@", marrSelectedStrings);

NSUInteger iCount = [marrSelectedStrings count]
for (NSUInteger i = 0; i < iCount; i++)
{
    NSLog(@"element %d: %@", i, [marrSelectedStrings objectAtIndex: i]);
}

使用其他UIViewController

self.label.text = [NSString stringWithFormat:@"%@", marrSelectedStrings];

字符串本身打印得很好。但是,对于数组,它取决于输出方法,控制台是否为其显示正确的特殊字符或代码。标签仅打印代码而不是真实字符。通过NSLog打印出来的内容如下:

Buffer: Röckdöts
Array: (
    R\U00f6ckd\U00f6ts
)
element 0: Röckdöts

标签上写着:

  

r \ U00f6ckd \ U00f6ts

我在添加到数组期间尝试使用stringWithUTF8String以及在将其分配给标签时进行编码,但它没有改变结果:

// adding with UTF8 encoding
[marrSelectedStrings addObject:[NSString stringWithUTF8String:[strBuffer UTF8String]]];

// printing to label with UTF8 encoding
self.label.text = [NSString stringWithUTF8String:[[NSString stringWithFormat:@"%@", marrSelectedStrings] UTF8String]];

是否有一种更简单的方法可以简单地使用正确的字符编码将数组打印到UILabel,而不是迭代数组并附加每个单词?

2 个答案:

答案 0 :(得分:1)

试试这个

NSString * result = [[marrSelectedStrings valueForKey:@"description"] componentsJoinedByString:@""];
self.label.text = result;

答案 1 :(得分:0)

试试这个

NSMutableArray *marrSelectedStrings = [[NSMutableArray alloc] init];
[marrSelectedStrings addObject:strBuffer];

NSString *description = [marrSelectedStrings description];
if (description) {
    const char *descriptionChar = [description cStringUsingEncoding:NSASCIIStringEncoding];
    if (descriptionChar) {
        NSString *prettyDescription = [NSString stringWithCString:descriptionChar encoding:NSNonLossyASCIIStringEncoding];
        if (prettyDescription) {
            description = prettyDescription;
        }
    }
}

NSLog(@"Array: %@", description);