RNelke
RNelke

Reputation: 87

iOS: Display NSArray of NSStrings in a label with special character encoding

I have several NSStrings which I add to an NSArray. The string may contain special characters. In the end I want to print the array to a UILabel.

The very simplified code (if you think I missed something, let me know):

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

In a different UIViewController:

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

The string itself prints out fine. For the array however, it depends on the output method, whether the console diplays the correct special character or code for it. The label only prints code instead of the real characters. The print out via NSLog looks like the following:

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

Whereas the label reads:

R\U00f6ckd\U00f6ts

I tried using stringWithUTF8String during the adding to the array as well as encoding during assigning it to the label like so, but it didn't change the result:

// 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]];

Is there an easier way to simply print the array with correct character encoding to the UILabel than iterating over the array and appending every single word?

Upvotes: 1

Views: 1100

Answers (2)

csaint
csaint

Reputation: 21

try like this

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

Upvotes: 0

Lithu T.V
Lithu T.V

Reputation: 20021

Try this

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

Upvotes: 1

Related Questions