OCruntime交换方法用在处理iOS版本跨度问题的解决

来源:互联网 发布:mysql 5.7.17.tar.gz 编辑:程序博客网 时间:2024/05/21 22:40


//交换方法用在处理iOS版本跨度问题的解决.


本文根据常用的UIImage 和 NSMutableArray简介.


#import "UIImage+WCY.h"

#import <objc/runtime.h>


@implementation UIImage (WCY)


//使用运行时的方法交互


//+ (void)initialize {

//    NSLog(@"initialize");

//}


// 加载的最早

+ (void)load {

   

   Method m1 =class_getClassMethod([UIImageclass],@selector(imageNamed:));

   Method m2 =class_getClassMethod([UIImageclass],@selector(imageWithName:));

    method_exchangeImplementations(m1, m2);

}


+ (UIImage *)imageWithName:(NSString *)name;{

    NSLog(@"imageWithName");

    

    //内部进行版本控制

   NSString *strName = name;

    

    if ([[UIDevicecurrentDevice].systemVersionfloatValue] > 8) {

        

        strName = [NSStringstringWithFormat:@"%@_ios7",name];

        

    }else {

        strName = name;

        

    }

    //这里用自己的否则会循环引用

  UIImage *image = [UIImageimageWithName:strName];

    

   if (image ==nil) {

        image = [UIImageimageWithName:name];

    }

    

   return image;

}


@end


#import "NSMutableArray+WCY.h"

#import <objc/runtime.h>


@implementation NSMutableArray (WCY)


+ (void)load {

   

    //替换数组的时候,是替换的类方法,

    

    Method m1 =class_getInstanceMethod(NSClassFromString(@"__NSArrayM"),@selector(addObject_wcy:));

    Method m2 =class_getInstanceMethod(NSClassFromString(@"__NSArrayM"),@selector(addObject:));

    

    method_exchangeImplementations(m1, m2);

}


- (void)addObject_wcy:(id)anObject;{

    

    

   if (anObject ==nil) {

//        [self addObject:@"this is nil"];

        [selfaddObject_wcy:@"this is nil"];

    }else {

//        [self addObject:anObject];

        [selfaddObject_wcy:anObject];

    }

    

}


@end


0 0