IOS使用 swizzle 解决一些错误

来源:互联网 发布:天刀脸型数据男 网盘 编辑:程序博客网 时间:2024/06/01 08:11
不知道你有没有经常遇到 这种 参数为 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}

然后在替换的方法里面 加入参数验证 
<pre name="code" class="objc">@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<cnt; 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



示例地址: 
http://download.csdn.net/detail/li6185377/6400383 
0 0
原创粉丝点击