分类使用runtime交换方法

来源:互联网 发布:九寨沟地震网络谣言 编辑:程序博客网 时间:2024/05/18 03:02


#import "NSArray+Safe.h"

#import <objc/runtime.h>  

@implementation NSArray (Safe)

//程序启动就会调用的方法

+ (void)load {


     Class class =  NSClassFromString(@"__NSArrayI");

    

    SEL system =@selector(objectAtIndex:);

    

    SEL custom =@selector(safeobjectAtIndex:);//自定义

    

    Method systemMethod =class_getInstanceMethod(class, system);

    

    Method customMethod =class_getInstanceMethod(class, custom);

    

    

    class_addMethod(class, custom,method_getImplementation(customMethod),method_getTypeEncoding(customMethod));

    

    method_exchangeImplementations(systemMethod,class_getInstanceMethod(class, custom));


}




- (id)safeobjectAtIndex:(NSInteger)index {


    if (index >self.count -1) {

        NSLog(@"数组越界了");

        

        returnnil;

    }else//返回已经调换过的方法

        return [selfsafeobjectAtIndex:index];

    }

}



0 0
原创粉丝点击