iOS如何解决某些方法低版本不支持的问题

来源:互联网 发布:php 数组写法 编辑:程序博客网 时间:2024/05/01 04:14
#import "NSString+avoidCrash.h"#import <objc/runtime.h>@implementation NSString (avoidCrash)+(void)load{    static dispatch_once_t onceToken;    dispatch_once(&onceToken, ^{                SEL systemSel = @selector(containsString:);        Method systemMethod = class_getInstanceMethod([self class], systemSel);        //如果没有找到,说明不包含此方法,需要动态添加此方法        if (systemMethod == NULL) {            SEL customSel = @selector(customContainsString:);            Method customMethod = class_getInstanceMethod([self class], customSel);                        BOOL isAdd = class_addMethod(self, systemSel, method_getImplementation(customMethod), method_getTypeEncoding(customMethod));                        if (!isAdd) {                NSLog(@"%@ runtime add method 'customContainsString:' failed",NSStringFromClass([self class]));            }        }            });}-(BOOL)customContainsString:(NSString *)str{    NSRange range = [self rangeOfString:str];        if (range.location < self.length && range.length > 0) {        return YES;    }        return NO;}@end

在实际的开发过程当中,经常会遇到一些方法低版本不支持的问题,往往需要加很多判断,造成代码很多,程序很冗余,总而言之就是不爽。
0 0
原创粉丝点击