1

我有几个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有没有比迭代数组并附加每个单词更简单的方法来简单地打印具有正确字符编码的数组?

4

2 回答 2

1

尝试这个

NSString * result = [[marrSelectedStrings valueForKey:@"description"] componentsJoinedByString:@""];
self.label.text = result;
于 2013-06-12T15:27:56.163 回答
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);
于 2017-05-29T05:59:10.253 回答