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

本文介绍了如何在Swift项目中使用runtime,特别是在Swift代码中处理UIButton的重复点击问题。由于Swift没有Objective-C的运行时消息机制,但继承自NSObject的类仍遵循Objective-C的runtime。通过@objc和dynamic关键字,可以实现对Swift类和属性的runtime操作。文中提供了使用runtime防止UIButton重复点击的代码示例,并提及Swift的initialize方法用于类似load的功能。还提到了Swift的CSSwiftExtension项目作为示例参考。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在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集合, 包含了一些常见的方法.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值