NSBundle+DAUtils.m 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. //
  2. // NSBundle+DAUtils.m
  3. // LanguageSettingsDemo
  4. //
  5. // Created by DarkAngel on 2017/5/4.
  6. // Copyright © 2017年 暗の天使. All rights reserved.
  7. //
  8. #import "NSBundle+DAUtils.h"
  9. #import "DAConfig.h"
  10. #import <objc/runtime.h>
  11. @interface DABundle : NSBundle
  12. @end
  13. @implementation NSBundle (DAUtils)
  14. + (BOOL)isChineseLanguage
  15. {
  16. NSString *currentLanguage = [self currentLanguage];
  17. if ([currentLanguage hasPrefix:@"zh-Hans"]) {
  18. return YES;
  19. } else {
  20. return NO;
  21. }
  22. }
  23. + (NSString *)currentLanguage
  24. {
  25. return [DAConfig userLanguage] ? : [NSLocale preferredLanguages].firstObject;
  26. }
  27. + (void)load
  28. {
  29. static dispatch_once_t onceToken;
  30. dispatch_once(&onceToken, ^{
  31. //动态继承、交换,方法类似KVO,通过修改[NSBundle mainBundle]对象的isa指针,使其指向它的子类DABundle,这样便可以调用子类的方法;其实这里也可以使用method_swizzling来交换mainBundle的实现,来动态判断,可以同样实现。
  32. object_setClass([NSBundle mainBundle], [DABundle class]);
  33. });
  34. }
  35. @end
  36. @implementation DABundle
  37. - (NSString *)localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)tableName
  38. {
  39. if ([DABundle uw_mainBundle]) {
  40. return [[DABundle uw_mainBundle] localizedStringForKey:key value:value table:tableName];
  41. } else {
  42. return [super localizedStringForKey:key value:value table:tableName];
  43. }
  44. }
  45. + (NSBundle *)uw_mainBundle
  46. {
  47. if ([NSBundle currentLanguage].length) {
  48. NSString *path = [[NSBundle mainBundle] pathForResource:[NSBundle currentLanguage] ofType:@"lproj"];
  49. if (path.length) {
  50. return [NSBundle bundleWithPath:path];
  51. }
  52. }
  53. return nil;
  54. }
  55. @end