NSNumber+YYAdd.m 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. //
  2. // NSNumber+YYAdd.m
  3. // YYKit <https://github.com/ibireme/YYKit>
  4. //
  5. // Created by ibireme on 13/8/24.
  6. // Copyright (c) 2015 ibireme.
  7. //
  8. // This source code is licensed under the MIT-style license found in the
  9. // LICENSE file in the root directory of this source tree.
  10. //
  11. #import "NSNumber+YYAdd.h"
  12. #import "NSString+YYAdd.h"
  13. #import "YYKitMacro.h"
  14. YYSYNTH_DUMMY_CLASS(NSNumber_YYAdd)
  15. @implementation NSNumber (YYAdd)
  16. + (NSNumber *)numberWithString:(NSString *)string {
  17. NSString *str = [[string stringByTrim] lowercaseString];
  18. if (!str || !str.length) {
  19. return nil;
  20. }
  21. static NSDictionary *dic;
  22. static dispatch_once_t onceToken;
  23. dispatch_once(&onceToken, ^{
  24. dic = @{@"true" : @(YES),
  25. @"yes" : @(YES),
  26. @"false" : @(NO),
  27. @"no" : @(NO),
  28. @"nil" : [NSNull null],
  29. @"null" : [NSNull null],
  30. @"<null>" : [NSNull null]};
  31. });
  32. id num = dic[str];
  33. if (num) {
  34. if (num == [NSNull null]) return nil;
  35. return num;
  36. }
  37. // hex number
  38. int sign = 0;
  39. if ([str hasPrefix:@"0x"]) sign = 1;
  40. else if ([str hasPrefix:@"-0x"]) sign = -1;
  41. if (sign != 0) {
  42. NSScanner *scan = [NSScanner scannerWithString:str];
  43. unsigned num = -1;
  44. BOOL suc = [scan scanHexInt:&num];
  45. if (suc)
  46. return [NSNumber numberWithLong:((long)num * sign)];
  47. else
  48. return nil;
  49. }
  50. // normal number
  51. NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
  52. [formatter setNumberStyle:NSNumberFormatterDecimalStyle];
  53. return [formatter numberFromString:string];
  54. }
  55. @end