NSDictionary+HWDUtil.m 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. // Tencent is pleased to support the open source community by making vap available.
  2. //
  3. // Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
  4. //
  5. // Licensed under the MIT License (the "License"); you may not use this file except in
  6. // compliance with the License. You may obtain a copy of the License at
  7. //
  8. // http://opensource.org/licenses/MIT
  9. //
  10. // Unless required by applicable law or agreed to in writing, software distributed under the License is
  11. // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
  12. // either express or implied. See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #import "NSDictionary+HWDUtil.h"
  15. #define HWD_RETURN_VALUE(_type_, _default_) \
  16. if (!key) return _default_; \
  17. id value = self[key]; \
  18. if (!value || value == [NSNull null]) return _default_; \
  19. if ([value isKindOfClass:[NSNumber class]]) return ((NSNumber *)value)._type_; \
  20. if ([value isKindOfClass:[NSString class]]) return ((NSString *)value)._type_; \
  21. return _default_;
  22. @implementation NSDictionary (HWDUtil)
  23. - (CGFloat)hwd_floatValue:(NSString *)key {
  24. HWD_RETURN_VALUE(floatValue, 0.0);
  25. }
  26. - (NSInteger)hwd_integerValue:(NSString *)key {
  27. HWD_RETURN_VALUE(integerValue, 0);
  28. }
  29. - (NSString *)hwd_stringValue:(NSString *)key {
  30. NSString *defaultValue = @"";
  31. if (!key) return defaultValue;
  32. id value = self[key];
  33. if (!value || value == [NSNull null]) return defaultValue;
  34. if ([value isKindOfClass:[NSString class]]) return value;
  35. if ([value isKindOfClass:[NSNumber class]]) return ((NSNumber *)value).description;
  36. return defaultValue;
  37. }
  38. - (NSDictionary *)hwd_dicValue:(NSString *)key {
  39. if (!key) {
  40. return nil;
  41. }
  42. id value = self[key];
  43. if (![value isKindOfClass:[NSDictionary class]]) {
  44. return nil;
  45. }
  46. return value;
  47. }
  48. - (NSArray *)hwd_arrValue:(NSString *)key {
  49. if (!key) {
  50. return nil;
  51. }
  52. id value = self[key];
  53. if (![value isKindOfClass:[NSArray class]]) {
  54. return nil;
  55. }
  56. return value;
  57. }
  58. @end