Skip to content

Instantly share code, notes, and snippets.

@tony0x59
Last active July 19, 2017 23:15
Show Gist options
  • Save tony0x59/9966962 to your computer and use it in GitHub Desktop.
Save tony0x59/9966962 to your computer and use it in GitHub Desktop.
使用Method swizzling方法修改常用函数行为
//
// 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