国际化处理时候,也要考虑NSLocale问题。
本地化封装了关于语言,文化以及技术约定和规范的信息。用于提供于用户所处地域相关的定制化信息和首选项信息的设置。通过获取用户的本地化信息设置,我们可以为用户提供更加友好人性化的界面设置,包括更改应用程序的界面的语言,货币类型,数字,日期格式的格式化,提供正确的地理位置显示等等。IOS内置为应用程序的开发提供了很好的本地化机制,良好的本地化意味着应用程序可以为更多的用户提供服务。其中NSLocale类的的主要作用便是用来封装本地化相关的各种信息,下面简单列举下NSLocale的一些方法,但NSLocale更多是使用在对数字,时间日期本地化的处理的过程。
1.创建本地化对象
2 | NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@ "en_US" ]; |
5 | [NSLocale currentLocale] |
2.获取系统本地化信息
02 | [NSLocale availableLocaleIdentifiers] ; |
05 | [NSLocale ISOCountryCodes] ; |
08 | [NSLocale ISOCurrencyCodes] ; |
11 | [NSLocale ISOLanguageCodes] ; |
3.获取当前系统设置语言的标识符
1 | [[NSLocale currentLocale] localeIdentifier]; |
3 | [[NSLocale currentLocale] objectForKey:NSLocaleIdentifier]; |
4.获取本地化对象的具体内容
1 | NSLocale *local = [NSLocale currentLocale]; |
3 | [local objectForKey:NSLocaleIdentifier]; |
5 | [local objectForKey: NSLocaleLanguageCode]; |
key值参见NSLocale Calendar Keys
5.获取当前语言的排版方向和字符方向
1 | [NSLocale lineDirectionForLanguage:[[NSLocale currentLocale] objectForKey:NSLocaleLanguageCode]; |
3 | [NSLocale characterDirectionForLanguage:[[NSLocale currentLocale] objectForKey:NSLocaleLanguageCode] ; |
6.获取用户的语言偏好设置列表,该列表对应于IOS中Setting>General>Language弹出的面板中的语言列表。
1 | [NSLocale preferredLanguages] |
第一个元素即为当前用户设置的语言
![在此输入图片描述](https://i-blog.csdnimg.cn/blog_migrate/2543a1a1f4b7005318389e475779340b.png)
7.监听用户本地化设置的消息
1 | [[NSNotificationCenter defaultCenter] addObserver:self |
2 | selector: @selector (localChangedHandler:) |
3 | name:NSCurrentLocaleDidChangeNotification object:nil]; |
8.以本地化方式获取国际化信息的显示名称
1 | NSLocale *curLocal = [[NSLocale alloc]initWithLocaleIdentifier:@ "zh-Hans" ] ; |
3 | NSLog(@ "%@" ,[curLocal displayNameForKey:NSLocaleIdentifier value:@ "fr_FR" ] ); |
5 | curLocal = [[NSLocale alloc]initWithLocaleIdentifier:@ "zh-Hant" ] ; |
7 | NSLog(@ "%@" ,[curLocal displayNameForKey:NSLocaleIdentifier value:@ "fr_FR" ] ); |
NSLocale
若你只开发中国区的应用,需要保证用户修改当前语言环境时应用的显示不发生变化。而像NSDateFormatter这样的类,会根据设备的设置,自动返回不同语言的数据。为了保证返回数据的语言一致,我们需要设置NSLocale。
2 | NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@ "zh" ]; |
3 | NSDateFormatter *secondDateFormatter = [[NSDateFormatter alloc] init]; |
4 | [secondDateFormatter setDateFormat:@ "cccc" ]; |
5 | secondDateFormatter.locale = locale; |
6 | NSDate *date = [NSDate date]; |
7 | NSLog(@ "%@" , [secondDateFormatter stringFromDate:date]); |
当然,像上面的需求很罕见。
作为大家都不常用的一个类,NSLocale类是将与国家和语言相关的信息进行简单的组合,包括货币,文学方面的信息。
货币:货币的国际名称(人民币的国际货币名称是CNY);货币符号(人民币的国际货币符号是¥)
文学:标点符号,文字的书写顺序(左右顺序),引用的起止符号等等
若做金融一类的应用可能会用到NSLocale这个类。
这个类稍微了解即可。