在模拟器的设置中更改区域格式,但应用中的区域设置不变
问题描述:
我使用NSDateFormatter的实例来帮助在我的应用中显示日期字符串,但是在模拟器中的“美国”到“英国”,设置中的示例显示日期为“2014年1月5日”,证明更改成功。但是当我在模拟器中打开我的应用时,日期仍然是“2014年1月5日”。 我用下面的代码来检查我的应用程序的语言环境:在模拟器的设置中更改区域格式,但应用中的区域设置不变
NSLocale *locale = [NSLocale currentLocale];
NSString *currentLocale = [locale objectForKey:NSLocaleIdentifier];
NSLog(@"Current locale is %@", currentLocale);
而且记录:当前语言环境是en_US。 似乎我的应用程序在模拟器设置中没有得到当前的语言环境。它应该是我在模拟器设置中更改语言环境,并且我的应用程序可以反映更改。有什么不对的吗? 日期格式代码是
static NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateStyle = NSDateFormatterMediumStyle;
dateFormatter.timeStyle = NSDateFormatterNoStyle;
self.dateLabel.text = [dateFormatter stringFromDate:item.dateCreated];
我使用iPhone模拟器版本8.1时,Xcode版本6.1.1,iOS的8.1,SDK 8.1
的dateFormatter代码被置于一个视图控制器的viewWillAppear中的方法,区域格式更改后,并创建一个新的视图控制器仍然呈现旧的区域设置。同样的结果甚至杀死了应用程序我在表格视图中注册区域设置更改通知并刷新它。它可以反映语言环境的变化。无法理解差异。
答
你必须设置你的NSDateFormatter
NSLocale *locale = [NSLocale currentLocale];
NSString *currentLocale = [locale objectForKey:NSLocaleIdentifier];
NSLog(@"Current locale is %@", currentLocale);
static NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setLocale:locale]; // <- Here
dateFormatter.dateStyle = NSDateFormatterMediumStyle;
dateFormatter.timeStyle = NSDateFormatterNoStyle;
self.dateLabel.text = [dateFormatter stringFromDate:item.dateCreated];
在setLocale之前,在设置中更改为“英国”后,currentLocale仍为“en_US”。所以[dateFormatter setLocale:locale];没有帮助。 – AngleZhou 2014-12-03 10:09:02
这是因为模拟器正在使用您的Mac的语言环境,尽管您从模拟器设置更改了语言环境。如果您在需要线路的实际设备上进行测试。 – sleepwalkerfx 2014-12-03 10:14:28
感谢您的设备建议,虽然我还没有尝试过设备上的应用程序。我想现在在模拟器上工作。 dateFormatter代码放在一个视图控制器的viewWillAppear方法中,在区域格式更改后,创建一个新的视图控制器仍然呈现旧的区域格式。同样的结果甚至杀死了应用程序我在表视图中注册了语言环境更改通知并进行刷新。它可以反映语言环境的变化。无法理解差异。任何想法? – AngleZhou 2014-12-03 12:48:28