iOS --- 如何在Swift项目中使用runtime?

在Objective-C的项目中, 经常遇到通过runtime来获取类和对象的成员变量, 属性, 方法, 在此基础上可以实现method swizzling.
关于runtime的相关内容, 请参考博客:
iOS — 理解Runtime机制及其使用场景
iOS—防止UIButton重复点击的三种实现方式
iOS — 使用runtime解决3D Touch导致UIImagePicker崩溃的问题
JSPatch即使用JavaScriptCore.framework, 使用JS代码调用任何OC的原生接口, 通过runtime来替换任意OC的原生方法, 以此来实现实时地修复线上bug.

Swift中如何使用runtime

Swift代码中已经没有了Objective-C的运行时消息机制, 在代码编译时即确定了其实际调用的方法. 所以纯粹的Swift类和对象没有办法使用runtime, 更不存在method swizzling.
为了兼容Objective-C, 凡是继承NSObject的类都会保留其动态性, 依然遵循Objective-C的运行时消息机制, 因此可以通过runtime获取其属性和方法, 实现method swizzling.
请看如下的代码:

//
//  UIButton+CSExtension.swift
//  CSSwiftExtension
//
//  Created by Chris Hu on 16/6/20.
//  Copyright © 2016年 icetime17. All rights reserved.
//

import UIKit

// MARK: - UIButton Related

public extension UIButton {

    private struct cs_associatedKeys {

        static var accpetEventInterval  = "cs_acceptEventInterval"
        static var acceptEventTime      = "cs_acceptEventTime"

    }

    // 重复点击的间隔
    var cs_accpetEventInterval: NSTimeInterval {
        get {
            if let accpetEventInterval = objc_getAssociatedObject(self, &cs_associatedKeys.accpetEventInterval) as? NSTimeInterval {
                return accpetEventInterval
            }

            return 1.0
        }

        set {
            objc_setAssociatedObject(self, &cs_associatedKeys.accpetEventInterval, newValue as NSTimeInterval, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }

    var cs_acceptEventTime: NSTimeInterval {
        get {
            if let acceptEventTime = objc_getAssociatedObject(self, &cs_associatedKeys.acceptEventTime) as? NSTimeInterval {
                return acceptEventTime
            }

            return 1.0
        }

        set {
            objc_setAssociatedObject(self, &cs_associatedKeys.acceptEventTime, newValue as NSTimeInterval, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }

    override public class func initialize() {
        let before: Method = class_getInstanceMethod(self, #selector(UIButton.sendAction(_:to:forEvent:)))
        let after: Method  = class_getInstanceMethod(self, #selector(UIButton.cs_sendAction(_:to:forEvent:)))

        method_exchangeImplementations(before, after)
    }

    func cs_sendAction(action: Selector, to target: AnyObject?, forEvent event: UIEvent?) {
        if NSDate().timeIntervalSince1970 - self.cs_acceptEventTime < self.cs_accpetEventInterval {
            return
        }

        if self.cs_accpetEventInterval > 0 {
            self.cs_acceptEventTime = NSDate().timeIntervalSince1970
        }

        self.cs_sendAction(action, to: target, forEvent: event)
    }

}

以上, 即通过runtime的方式解决UIButton的重复点击问题.
UIButton继承自NSObject, 因此遵循runtime. 事实上, 对于基本框架如Foundation, UIKit等, 都可以使用runtime.
这里, 要注意Swift的代码与Objective-C代码的语法区别.
同时, 对于一般OC代码的method swizzling, 在load方法中执行即可. 而Swift没有load, 所以要在initialize中执行.
使用方式:

btn.cs_accpetEventInterval = 1.0

Swift中的@objc和dynamic关键字

继承自NSObject的类都遵循runtime, 那么纯粹的Swift类呢?
在属性和方法之前加上@objc关键字, 则一般情况下可以在runtime中使用了. 但有一些情况下, Swift会做静态优化而无法使用runtime.
要想完全使得属性和方法被动态调用, 必须使用dynamic关键字. 而dynamic关键字会隐式地加上@objc来修饰.
获取Swift类的runtime信息的方法, 要加上Swift模块名:

id cls = objc_getClass("DemoSwift.MySwiftClass")

关于Demo

本文的Demo请参考CSSwiftExtension.
这是是一个Swift的extension集合, 包含了一些常见的方法.

猜你喜欢

转载自blog.csdn.net/icetime17/article/details/51817534