码迷,mamicode.com
首页 > 移动开发 > 详细

ios runtime swizzle

时间:2015-03-29 22:16:21      阅读:242      评论:0      收藏:0      [点我收藏+]

标签:ios   runtime   swizzle   ios runtime swizzle   

<pre name="code" class="objc">#import <objc/runtime.h>

@implementation NSObject(Extension)
+ (void)swizzleClassMethod:(Class)class originSelector:(SEL)originSelector otherSelector:(SEL)otherSelector
{
    Method otherMehtod = class_getClassMethod(class, otherSelector);
    Method originMehtod = class_getClassMethod(class, originSelector);
    // 交换2个方法的实现
    method_exchangeImplementations(otherMehtod, originMehtod);
}

+ (void)swizzleInstanceMethod:(Class)class originSelector:(SEL)originSelector otherSelector:(SEL)otherSelector
{
    Method otherMehtod = class_getInstanceMethod(class, otherSelector);
    Method originMehtod = class_getInstanceMethod(class, originSelector);
    // 交换2个方法的实现
    method_exchangeImplementations(otherMehtod, originMehtod);
}
@end

@implementation NSArray(Extension)
+ (void)load
{
    [self swizzleInstanceMethod:NSClassFromString(@"__NSArrayI") originSelector:@selector(objectAtIndex:) otherSelector:@selector(hm_objectAtIndex:)];
}

- (id)hm_objectAtIndex:(NSUInteger)index
{
    if (index < self.count) {
        return [self hm_objectAtIndex:index];
    } else {
        return nil;
    }
}

@end

@implementation NSMutableArray(Extension)
+ (void)load
{
    [self swizzleInstanceMethod:NSClassFromString(@"__NSArrayM") originSelector:@selector(addObject:) otherSelector:@selector(hm_addObject:)];
    [self swizzleInstanceMethod:NSClassFromString(@"__NSArrayM") originSelector:@selector(objectAtIndex:) otherSelector:@selector(hm_objectAtIndex:)];
}

- (void)hm_addObject:(id)object
{
    if (object != nil) {
        [self hm_addObject:object];
    }
}

- (id)hm_objectAtIndex:(NSUInteger)index
{
    if (index < self.count) {
        return [self hm_objectAtIndex:index];
    } else {
        return nil;
    }
}
@end



ios runtime swizzle

标签:ios   runtime   swizzle   ios runtime swizzle   

原文地址:http://blog.csdn.net/zhangping871/article/details/44731441

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!