NSDictionary+AvoidCrash.m 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. //
  2. // NSDictionary+AvoidCrash.m
  3. // https://github.com/chenfanfang/AvoidCrash
  4. //
  5. // Created by mac on 16/9/21.
  6. // Copyright © 2016年 chenfanfang. All rights reserved.
  7. //
  8. #import "NSDictionary+AvoidCrash.h"
  9. #import "AvoidCrash.h"
  10. @implementation NSDictionary (AvoidCrash)
  11. + (void)avoidCrashExchangeMethod {
  12. static dispatch_once_t onceToken;
  13. dispatch_once(&onceToken, ^{
  14. [AvoidCrash exchangeClassMethod:self method1Sel:@selector(dictionaryWithObjects:forKeys:count:) method2Sel:@selector(avoidCrashDictionaryWithObjects:forKeys:count:)];
  15. });
  16. }
  17. + (instancetype)avoidCrashDictionaryWithObjects:(const id _Nonnull __unsafe_unretained *)objects forKeys:(const id<NSCopying> _Nonnull __unsafe_unretained *)keys count:(NSUInteger)cnt {
  18. id instance = nil;
  19. @try {
  20. instance = [self avoidCrashDictionaryWithObjects:objects forKeys:keys count:cnt];
  21. }
  22. @catch (NSException *exception) {
  23. NSString *defaultToDo = @"AvoidCrash default is to remove nil key-values and instance a dictionary.";
  24. [AvoidCrash noteErrorWithException:exception defaultToDo:defaultToDo];
  25. //处理错误的数据,然后重新初始化一个字典
  26. NSUInteger index = 0;
  27. id _Nonnull __unsafe_unretained newObjects[cnt];
  28. id _Nonnull __unsafe_unretained newkeys[cnt];
  29. for (int i = 0; i < cnt; i++) {
  30. if (objects[i] && keys[i]) {
  31. newObjects[index] = objects[i];
  32. newkeys[index] = keys[i];
  33. index++;
  34. }
  35. }
  36. instance = [self avoidCrashDictionaryWithObjects:newObjects forKeys:newkeys count:index];
  37. }
  38. @finally {
  39. return instance;
  40. }
  41. }
  42. @end