IOS使用 swizzle 解决一些错误

不知道你有没有经常遇到 这种 参数为 nil 的错误 或者是 数组错误。

 

而且现在在 多线程中 还是 大量使用 block 的情况下 要查找起来 实在是 太费劲了

所以 我用了个 取巧的办法(可能会导致你的逻辑错误) 用swizzle 来替换这些没验证的方法

我是按我自己 umeng 的 错误统计来写的 给出个 例子而已

 

  1. +(void)callSafeCategory
  2. {
  3. NSError* error = nil;
  4. [objc_getClass("__NSPlaceholderArray") jr_swizzleMethod:@selector(initWithObjects:count:) withMethod:@selector(SY_safeInitWithObjects:count:) error:&error];
  5. LOG_Error
  6. [objc_getClass("__NSArrayI") jr_swizzleMethod:@selector(objectAtIndex:) withMethod:@selector(SY_safeObjectAtIndex:) error:&error];
  7. LOG_Error
  8. [objc_getClass("__NSArrayM") jr_swizzleMethod:@selector(objectAtIndex:) withMethod:@selector(SY_safeObjectAtIndex:) error:&error];
  9. LOG_Error
  10. [objc_getClass("__NSArrayM") jr_swizzleMethod:@selector(addObject:) withMethod:@selector(SY_safeAddObject:) error:&error];
  11. LOG_Error
  12. [objc_getClass("__NSDictionaryI") jr_swizzleMethod:@selector(objectForKey:) withMethod:@selector(SY_safeObjectForKey:) error:&error];
  13. LOG_Error
  14. [objc_getClass("__NSDictionaryM") jr_swizzleMethod:@selector(objectForKey:) withMethod:@selector(SY_safeObjectForKey:) error:&error];
  15. LOG_Error
  16. [objc_getClass("__NSDictionaryM") jr_swizzleMethod:@selector(setObject:forKey:) withMethod:@selector(SY_safeSetObject:forKey:) error:&error];
  17. LOG_Error
  18. [NSURL jr_swizzleClassMethod:@selector(fileURLWithPath:isDirectory:) withClassMethod:@selector(SY_safeFileURLWithPath:isDirectory:) error:&error];
  19. LOG_Error
  20. [NSFileManager jr_swizzleMethod:@selector(enumeratorAtURL:includingPropertiesForKeys:options:errorHandler:) withMethod:@selector(SY_safeEnumeratorAtURL:includingPropertiesForKeys:options:errorHandler:) error:&error];
  21. LOG_Error
  22. }

然后在替换的方法里面 加入参数验证

  1.  
  2. @implementation NSArray(SYSafeCategory)
  3. -(id)SY_safeObjectAtIndex:(int)index{
  4. if(index>=0 && index < self.count)
  5. {
  6. return [self SY_safeObjectAtIndex:index];
  7. }
  8. else{
  9. #ifdef DEBUG
  10. NSAssert(NO,nil);
  11. #endif
  12. }
  13. return nil;
  14. }
  15. -(id)SY_safeInitWithObjects:(const id [])objects count:(NSUInteger)cnt
  16. {
  17. for (int i=0; i
  18. if(objects[i] == nil)
  19. return nil;
  20. }
  21. return [self SY_safeInitWithObjects:objects count:cnt];
  22. }
  23. @end
  24. @implementation NSMutableArray(SYSafeCategory)
  25. -(void)SY_safeAddObject:(id)anObject
  26. {
  27. if(anObject != nil){
  28. [self SY_safeAddObject:anObject];
  29. }
  30. }
  31. @end
    1. @implementation NSArray(SYSafeCategory)
posted @ 2014-01-10 15:43  忘删  阅读(770)  评论(4编辑  收藏  举报