不知道你有没有经常遇到 这种 参数为 nil 的错误 或者是 数组错误。
而且现在在 多线程中 还是 大量使用 block 的情况下 要查找起来 实在是 太费劲了
所以 我用了个 取巧的办法(可能会导致你的逻辑错误)
用swizzle 来替换这些没验证的方法
我是按我自己 umeng 的 错误统计来写的 给出个 例子而已
- +(void)callSafeCategory
- {
- NSError* error =
nil;
- [objc_getClass("__NSPlaceholderArray")
jr_swizzleMethod:@selector(initWithObjects:count:)
withMethod:@selector(SY_safeInitWithObjects:count:)
error:&error];
- LOG_Error
- [objc_getClass("__NSArrayI")
jr_swizzleMethod:@selector(objectAtIndex:)
withMethod:@selector(SY_safeObjectAtIndex:)
error:&error];
- LOG_Error
- [objc_getClass("__NSArrayM")
jr_swizzleMethod:@selector(objectAtIndex:)
withMethod:@selector(SY_safeObjectAtIndex:)
error:&error];
- LOG_Error
- [objc_getClass("__NSArrayM")
jr_swizzleMethod:@selector(addObject:) withMethod:@selector(SY_safeAddObject:)
error:&error];
- LOG_Error
- [objc_getClass("__NSDictionaryI")
jr_swizzleMethod:@selector(objectForKey:)
withMethod:@selector(SY_safeObjectForKey:)
error:&error];
- LOG_Error
- [objc_getClass("__NSDictionaryM")
jr_swizzleMethod:@selector(objectForKey:)
withMethod:@selector(SY_safeObjectForKey:)
error:&error];
- LOG_Error
- [objc_getClass("__NSDictionaryM")
jr_swizzleMethod:@selector(setObject:forKey:)
withMethod:@selector(SY_safeSetObject:forKey:)
error:&error];
- LOG_Error
- [NSURL
jr_swizzleClassMethod:@selector(fileURLWithPath:isDirectory:)
withClassMethod:@selector(SY_safeFileURLWithPath:isDirectory:)
error:&error];
- LOG_Error
- [NSFileManager
jr_swizzleMethod:@selector(enumeratorAtURL:includingPropertiesForKeys:options:errorHandler:)
withMethod:@selector(SY_safeEnumeratorAtURL:includingPropertiesForKeys:options:errorHandler:)
error:&error];
- LOG_Error
- }
然后在替换的方法里面 加入参数验证
-
- @implementation
NSArray(SYSafeCategory)
- -(id)SY_safeObjectAtIndex:(int)index{
- if(index>=0 &&
index < self.count)
- {
- return [self
SY_safeObjectAtIndex:index];
- }
- else{
- #ifdef
DEBUG
- NSAssert(NO,nil);
- #endif
- }
- return nil;
- }
- -(id)SY_safeInitWithObjects:(const id
[])objects count:(NSUInteger)cnt
- {
- for (int i=0;
i
- if(objects[i] ==
nil)
- return nil;
- }
- return [self
SY_safeInitWithObjects:objects count:cnt];
- }
- @end
- @implementation
NSMutableArray(SYSafeCategory)
- -(void)SY_safeAddObject:(id)anObject
- {
- if(anObject
!= nil){
- [self
SY_safeAddObject:anObject];
- }
- }
- @end
- @implementation
NSArray(SYSafeCategory)
IOS使用 swizzle 解决一些错误
原文:http://www.cnblogs.com/hanyis/p/3513843.html