开发者

objective-c how to encode NSArray with UTF8?

I have scandinavian alphabets in my array like æ, ø, å. With NSLog the output showed these alphabets as scrambled codes. How to encode NSArray with UTF8? Any help is appreciated.

I tried only:

NSArray *nnoWords = [[NSArray arrayWithArray:newNoWords] retain];
NSLog (@"nnoWords: %@ ", nnoWords);

newNoWords is a NSMutableArray. nnoWords containt normal objects like NSString hello, pear, apple, etc. taken from a txt file.


EDIT 29 august 2011:

nnoWords comes from this, converted to NSMutable and then back to NSArray, thus cal开发者_JS百科led nnoWords. And words.txt is encoded in UTF8.

     NSArray *noWords = [[NSArray alloc] initWithArray:
        [[NSString stringWithContentsOfFile:[[NSBundle mainBundle] 
    pathForResource:@"words" ofType:@"txt"]                                         
encoding:NSUTF8StringEncoding error:NULL] componentsSeparatedByString:@"\n"]];

I have also tried:

NSString *norsk = @"æ ø å";
    NSLog (@"%@", norsk);

And the output is correct:

2011-08-29 13:15:23.302 scanner2[29776:207] æ ø å


The problem is the Xcode console. If you view the output from Terminal.app, you will see it is as expected.

Test case:

//clang -framework Foundation -o log_utf8 log_utf8.m
#import <Foundation/Foundation.h>

int
main(void)
{
  NSString *word = @"en ord på Svenska";
  NSLog(@"%@", word);
}

Sample output:

StackOverflow$ clang -framework Foundation log_utf8.m -o log_utf8
StackOverflow$ ./log_utf8 
2011-08-28 20:10:09.268 log_utf8[65105:707] en ord på Svenska

If you are still seeing gibberish when you view the output from something other than Xcode's questionable built-in console, then you need to examine how you're getting your string data:

  • How does the text with non-ASCII characters enter your application?
  • What encoding does NSString think that text is in?
  • What encoding is it actually in? If the text comes from a file, then the file command might be able to answer this for you.


Try this:

NSLog(@"%S", [[theArray description] cStringUsingEncoding:NSUTF16LittleEndianStringEncoding]);

from this question: NSLog incorrect encoding

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜