NSMutableDictionary+NullSaf.m 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. //
  2. // NSMutableDictionary+NullSaf.m
  3. // EPurse
  4. //
  5. // Created by Apple on 2018/1/23.
  6. // Copyright © 2018年 北风小南巷. All rights reserved.
  7. //
  8. #import "NSMutableDictionary+NullSaf.h"
  9. #import<objc/runtime.h>
  10. @implementation NSMutableDictionary (NullSaf)
  11. - (void)swizzeMethod:(SEL)origSelector withMethod:(SEL)newSelector
  12. {
  13. Class class = [self class];
  14. Method originalMethod = class_getInstanceMethod(class, origSelector);//Method是运行时库的类
  15. Method swizzledMethod = class_getInstanceMethod(class, newSelector);
  16. BOOL didAddMethod = class_addMethod(class, origSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod));
  17. if (didAddMethod) {
  18. class_replaceMethod(class, newSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
  19. }else{
  20. method_exchangeImplementations(originalMethod, swizzledMethod);
  21. }
  22. }
  23. - (void)safe_setObject:(id)value forKey:(NSString* )key{
  24. if (value) {
  25. [self safe_setObject:value forKey:key];
  26. }else{
  27. //NSLog(@"[NSMutableDictionary setObject: forKey:%@]值不能为空;",key);
  28. }
  29. }
  30. - (void)safe_removeObjectForKey:(NSString *)key{
  31. if ([self objectForKey:key]) {
  32. [self safe_removeObjectForKey:key];
  33. }else{
  34. //NSLog(@"[NSMutableDictionary setObject: forKey:%@]值不能为空;",key);
  35. }
  36. }
  37. + (void)load{
  38. static dispatch_once_t onceToken;
  39. dispatch_once(&onceToken, ^{
  40. id obj = [[self alloc]init];
  41. [obj swizzeMethod:@selector(setObject:forKey:) withMethod:@selector(safe_setObject:forKey:)];
  42. [obj swizzeMethod:@selector(removeObjectForKey:) withMethod:@selector(safe_removeObjectForKey:)];
  43. });
  44. }
  45. @end