Saving Hebrew text to NSUserDefaults return strange encoding

旧城冷巷雨未停 提交于 2019-11-28 14:20:27

If you use NSLog(@"%@", ...) to print the description of an array or dictionary, all non-ASCII characters are printed using a \Unnnn escape sequence:

NSArray *a = [NSArray arrayWithObject:@"מערכת"];
NSLog(@"%@", a);

Output:

(
   "\U05de\U05e2\U05e8\U05db\U05ea"
)

(The reason is that the description method of NSArray and NSDictionary uses the Old-Style ASCII Property Lists format, which, as the name indicates, allows only ASCII characters.)

If you print the description of a string, all characters are properly displayed:

NSLog(@"%@", [a objectAtIndex:0]);

Output:

מערכת

So this is only a display issue.

Try doing something like this:

NSString *someObject = //your object that needs decode
        NSString *decodedObject = [NSString
            stringWithCString:[someObject cStringUsingEncoding:NSUTF8StringEncoding]
            encoding:NSNonLossyASCIIStringEncoding];
        NSLog(@"decodedObject = %@", decodedObject);

Edit: There's probably something wrong in your code someplace else because this:

NSMutableArray *tempArray = [[NSMutableArray alloc] init];
    [tempArray addObject:@"בדיקה"];

    [[NSUserDefaults standardUserDefaults] setObject:tempArray forKey:@"test"];
    [[NSUserDefaults standardUserDefaults] synchronize];    
    NSMutableArray *test2=[[NSUserDefaults standardUserDefaults] objectForKey:@"test"];    
    NSLog(@"test2: %@",[test2 objectAtIndex:0]);

works fine.

Well, can you post the code behind sharedPrefs?

When i tried to save a simple hebrew to userdefault it worked just fine.

NSString *tempKeyToStore = @"KEY";

NSMutableArray *tempArray = [[NSMutableArray alloc] init];

[tempArray addObject:@"שלום שלום"];

[[NSUserDefaults standardUserDefaults] setObject:tempArray forKey:tempKeyToStore];
[[NSUserDefaults standardUserDefaults] synchronize];

Read it later -

//
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

NSMutableArray *tempArray = [defaults objectForKey:@"KEY"];

for (NSString* str in tempArray)
{
    NSLog(@"%@", str);
}

Hope i helped..

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!