您的位置:首页 > 移动开发 > IOS开发

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

2016-05-16 11:21 816 查看
#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


在实际的开发过程当中,经常会遇到一些方法低版本不支持的问题,往往需要加很多判断,造成代码很多,程序很冗余,总而言之就是不爽。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ios