Last active
July 19, 2017 23:15
-
-
Save tony0x59/9966962 to your computer and use it in GitHub Desktop.
使用Method swizzling方法修改常用函数行为
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// NSObject+SafeCategory.m | |
// | |
// Created by Tony on 14-4-3. | |
// Copyright (c) 2014年 Tony. All rights reserved. | |
// | |
#import "NSObject+SafeCategory.h" | |
#import <JRSwizzle/JRSwizzle.h> | |
#define LOG_ERROR(err) \ | |
do { \ | |
if (err) { \ | |
NSLog(@"Error: %@", err); \ | |
err = nil; \ | |
} \ | |
} while(0) | |
@interface NSArray (SafeCategory) | |
- (id)TKSafe_objectAtIndex:(NSUInteger)index; | |
@end | |
@implementation NSArray (SafeCategory) | |
- (id)TKSafe_objectAtIndex:(NSUInteger)index | |
{ | |
if (index < self.count) { | |
return [self TKSafe_objectAtIndex:index]; | |
} else { | |
#ifdef DEBUG | |
NSAssert(NO, @"index %d > count %d", index, self.count); | |
#endif | |
return nil; | |
} | |
} | |
@end | |
@interface NSMutableArray (SafeCategory) | |
- (void)TKSafe_addObject:(id)anObject; | |
@end | |
@implementation NSMutableArray (SafeCategory) | |
- (void)TKSafe_addObject:(id)anObject | |
{ | |
if (anObject != nil) { | |
[self TKSafe_addObject:anObject]; | |
} else { | |
#ifdef DEBUG | |
NSAssert(NO, @"object is nil"); | |
#endif | |
} | |
} | |
@end | |
@implementation NSObject (SafeCategory) | |
+ (void)configureSafeMethods | |
{ | |
NSError *error = nil; | |
[[[NSArray array] class] jr_swizzleMethod:@selector(objectAtIndex:) | |
withMethod:@selector(TKSafe_objectAtIndex:) | |
error:&error]; | |
LOG_ERROR(error); | |
[[[NSMutableArray array] class] jr_swizzleMethod:@selector(objectAtIndex:) | |
withMethod:@selector(TKSafe_objectAtIndex:) | |
error:&error]; | |
LOG_ERROR(error); | |
[[[NSMutableArray array] class] jr_swizzleMethod:@selector(addObject:) | |
withMethod:@selector(TKSafe_addObject:) | |
error:&error]; | |
LOG_ERROR(error); | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment