NSMutableDictionary+TBXSafe.m 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. //
  2. // NSMutableDictionary+TBXSafe.m
  3. // assemble
  4. //
  5. // Created by apple on 2020/11/2.
  6. // Copyright © 2020 kingsunsoft. All rights reserved.
  7. //
  8. #import "NSMutableDictionary+TBXSafe.h"
  9. #import <objc/runtime.h>
  10. #import "NSObject+Swizzling.h"
  11. @implementation NSMutableDictionary (TBXSafe)
  12. + (void)load {
  13. //只执行一次这个方法
  14. static dispatch_once_t onceToken;
  15. dispatch_once(&onceToken, ^{
  16. // 替换 removeObjectForKey:
  17. NSString *tmpRemoveStr = @"removeObjectForKey:";
  18. NSString *tmpSafeRemoveStr = @"safeMutable_removeObjectForKey:";
  19. [NSObject exchangeInstanceMethodWithSelfClass:NSClassFromString(@"__NSDictionaryM")
  20. originalSelector:NSSelectorFromString(tmpRemoveStr) swizzledSelector:NSSelectorFromString(tmpSafeRemoveStr)];
  21. // 替换 setObject:forKey:
  22. NSString *tmpSetStr = @"setObject:forKey:";
  23. NSString *tmpSafeSetRemoveStr = @"safeMutable_setObject:forKey:";
  24. [NSObject exchangeInstanceMethodWithSelfClass:NSClassFromString(@"__NSDictionaryM")
  25. originalSelector:NSSelectorFromString(tmpSetStr) swizzledSelector:NSSelectorFromString(tmpSafeSetRemoveStr)];
  26. });
  27. }
  28. #pragma mark --- implement method
  29. /**
  30. 根据akey 移除 对应的 键值对
  31. @param aKey key
  32. */
  33. - (void)safeMutable_removeObjectForKey:(id<NSCopying>)aKey {
  34. if (!aKey) {
  35. return;
  36. }
  37. [self safeMutable_removeObjectForKey:aKey];
  38. }
  39. /**
  40. 将键值对 添加 到 NSMutableDictionary 内
  41. @param anObject 值
  42. @param aKey 键
  43. */
  44. - (void)safeMutable_setObject:(id)anObject forKey:(id<NSCopying>)aKey {
  45. if (!anObject) {
  46. return;
  47. }
  48. if (!aKey) {
  49. return;
  50. }
  51. return [self safeMutable_setObject:anObject forKey:aKey];
  52. }
  53. @end