2011-02-04 85 views
2

我有一个NSString对象,并希望将其更改为unichar。是否有可能将NSString转换为unichar

int decimal = [[temp substringFromIndex:2] intValue]; // decimal = 12298 

NSString *hex = [NSString stringWithFormat:@"0x%x", decimal]; // hex = 0x300a 

NSString *chineseChar = [NSString stringWithFormat:@"%C", hex]; 

// This statement log a different Chinese char every time I run this code 
NSLog(@"%@",chineseChar); 

当我看到日志时,每次运行我的代码时都会给出不同的字符。 m我错过了什么......?

回答

5

%C format specifier以16位Unicode字符(unichar)作为输入,而不是NSString。你传递的是一个NSString,它被重新解释为一个整数字符;由于每次运行时字符串都可以存储在内存中的不同地址处,因此可以将该地址作为整数来使用,这就是为什么每次运行代码时都会得到不同的中文字符的原因。

在人物只是通过为整数:

unichar decimal = 12298; 
NSString *charStr = [NSString stringWithFormat:@"%C", decimal]; 
// charStr is now a string containing the single character U+300A, 
// LEFT DOUBLE ANGLE BRACKET 
+0

感谢dude..It就像一个魅力。 – 2011-02-05 11:11:06

相关问题