美文网首页
iOS之兼容问题

iOS之兼容问题

作者: PanPan1127 | 来源:发表于2016-01-04 14:18 被阅读1623次

    iOS之兼容问题

    iOS 项目向老版本兼容的常规和非常规方法。

    概念

    Deplyment TargetAPP能支持的最低系统版本,如要支持iOS6以上,就设置成iOS6即可。

    Base SDK用来编译APP的SDK(Software Development Kit)的版本,一般保持当前XCode支持的最新的就好。

    SDK其实就是包含了所有的你要用到的头文件、链接库的集合,你的APP里面用的各种类、函数,能编译、链接成最后的安装包,就要靠它,苹果每次升级系统,新推出的各种API,也是在SDK里面。所以一般Base SDK肯定是大于等于Deployment Target的版本。

    注意:既然Base SDK的版本 >= Deployment Target的版本,那么就要小心了,因为“只要用到的类、方法,在当前的Base SDK版本里面存在,就可以编译通过!但是一旦运行APP的手机的系统版本低于这些类、方法的最低版本要求,APP就会Crash!”

    只在编译时生效。是纯粹的文本替换。

    #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000
        NSLog(@"Tutuge");
    #endif
    

    被宏定义包起来的代码是否会执行,在编译时就决定好了,无论你是用什么系统运行,宏定义再也没有什么卵用。

    编译时检查 SDK 版本,运行时检查系统版本。

    这个是最基本的适配手段,二者均不能少。

    所用SDK 版本检测 宏如下:

    1. __IPHONE_OS_VERSION_MAX_ALLOWED: 值等于Base SDK,即用于检查SDK版本的
    2. __IPHONE_OS_VERSION_MIN_REQUIRED: 值等于Deployment Target,检查支持的最小系统版本。

    运行时检查系统版本:

    f ([UIDevice currentDevice].systemVersion.floatValue > 8.0f) {
        // ...
    }
    

    综合以上,如要实现使用 ios8新的 UIAlertCtrl 的例子:

    // 编译时判断:检查SDK版本
    #if __IPHONE_OS_VERSION_MAX_ALLOWED > 80000
        // 运行时判断:检查当前系统版本
        if ([UIDevice currentDevice].systemVersion.floatValue > 8.0f) {
            UIAlertController *alertController =
            [UIAlertController alertControllerWithTitle:@"Tutuge"
                                                message:@"Compatibility"
                                         preferredStyle:UIAlertControllerStyleAlert];
            [alertController addAction:[UIAlertAction actionWithTitle:@"Cancel"
                                                                style:UIAlertActionStyleCancel
                                                              handler:^(UIAlertAction *action) {
                                                                  NSLog(@"Cancel");
                                                              }]];
            [self presentViewController:alertController animated:YES completion:nil];
        } else {
            // 用旧的代替
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Tutuge"
                                                                message:@"Compatibility"
                                                               delegate:nil
                                                      cancelButtonTitle:@"Cancel"
                                                      otherButtonTitles:nil];
            [alertView show];
        }
    #else
        // ...
    #endif
    
    

    Weakly Linked--运行时检查类、方法是否可用

    对于iOS4.2以上的,有NS_CLASS_AVAILABLE标示的类,可以如下判断是否可用:

    #if __IPHONE_OS_VERSION_MAX_ALLOWED > 80000
        // Weakly Linked判断
        if ([UIAlertController class]) {
            // 使用UIAlertController...
        } else {
            // 使用旧的方案...
        }
    #endif
    

    或者

    Class class = NSClassFromString (@"UIAlertController");
    if (class) {
        // 使用UIAlertController...
    } else {
        // 使用旧的方案...
    }
    

    对于方法的可用性判断:

    if ([UITableViewCell instancesRespondToSelector:@selector (setSeparatorInset:)]) {
        // ...
    } else {
        // ...
    }
    

    method Swizzling 做兼容

    在 +(void)load 方法里做替换

    在Objective-C中,运行时会自动调用每个类的两个方法。

    + (void)load会在类、Category初始加载时调用.

    + (void)initialize会在第一次调用类的类方法或实例方法之前被调用。

    需要注意的是,+ (void)initialize是可以被Category覆盖重写的,并且有多个Category都重写了+ (void)initialize方法时,只会运行其中一个,所以在+ (void)initialize里面做Method Swizzling显然是不行的。

    而+ (void)load方法只要实现了,就一定会调用。具体为什么大家可以自行阅读Runtime的源码,或者查阅相关文章。

    用 dispatch_once 实行单例模式

    因为Method Swizzling的影响是全局的,而且一旦多次调用,会出错,所以这个时候用dispatch_once就再合适不过了~

    实例:

    // 创建Category
    @implementation UILabel (TTGCompatibility)
    
    + (void)load {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            // 先判断系统版本,尽量减少Runtime的作用范围
            if ([UIDevice currentDevice].systemVersion.floatValue < 7.0f) {
                // Method Swizzling
                // initWithFrame
                Method oriMethod = class_getInstanceMethod(self, @selector(initWithFrame:));
                Method newMethod = class_getInstanceMethod(self, @selector(compatible_initWithFrame:));
                method_exchangeImplementations(oriMethod, newMethod);
                
                // initWithCoder...
            }
        });
    }
    
    // initWithFrame
    - (id)compatible_initWithFrame:(CGRect)frame {
        id newSelf = [self compatible_initWithFrame:frame];
        // 设置透明背景色
        ((UILabel *)newSelf).backgroundColor = [UIColor clearColor];
        return newSelf;
    }
    
    // initWithCoder..
    
    

    运行时添加“Dummy”方法,减少代码改动

    为旧版本不存在的方法提供一个“假的”替代方法,防止因新API找不到而导致的Crash。

    实例:
    以UITableViewCell的“setSeparatorInset:”方法为例,在iOS6中,压根就不存在separatorInset,但是现有的代码里面大量的调用了这个方法,怎么办?

    这个时候就可以用Runtime的手段,在运行时添加一个Dummy方法,去“代替接收”setSeparatorInset消息,防止在iOS6上的Crash。

    @implementation UITableViewCell (TTGCompatibility)
    
    + (void)load {
    // 编译时判断SDK
    #if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_7_0
        // 运行时判断系统版本
        if ([UIDevice currentDevice].systemVersion.floatValue < 7.0f) {
            Method newMethod = class_getInstanceMethod(self, @selector(compatible_setSeparatorInset:));
            // 增加Dummy方法
            class_addMethod(
                    self,
                    @selector(setSeparatorInset:),
                    method_getImplementation(newMethod),
                    method_getTypeEncoding(newMethod));
        }
    #endif
    }
    
    // setSeparatorInset: 的Dummy方法
    - (void)compatible_setSeparatorInset:(UIEdgeInsets) inset {
        // 空方法都可以,只是为了接收setSeparatorInset:消息。
    }
    
    

    相关文章

      网友评论

          本文标题:iOS之兼容问题

          本文链接:https://www.haomeiwen.com/subject/izcahttx.html