2013-06-12 23 views
1

我有幾個NSStrings,我將其添加到NSArray。該字符串可能包含特殊字符。最後我想打印數組到UILabeliOS:在具有特殊字符編碼的標籤中顯示NSStrings的NSArray

非常簡單的代碼(如果你認爲我錯過了什麼,讓我知道):

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而不是迭代數組並追加每個單詞?

回答

1

試試這個

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

非常感謝您!此外,該解決方案擺脫醜陋的括號。 – RNelke

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);