Swift 函数调配/运行时 [英] Swift function swizzling / runtime

查看:45
本文介绍了Swift 函数调配/运行时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Swift 之前,在 Objective-C 中,我会使用 <objc/runtime.h> 来混合或钩子类中的方法.

Before Swift, in Objective-C I would swizzle or hook methods in a class using <objc/runtime.h>.

如果有人有任何关于修改 Swift 的运行时和挂钩函数(如 CydiaSubstrate 和其他在该领域有帮助的库)主题的信息,请告诉我.

If anyone has any info on the topic of modifying Swift's runtime and hooking functions like CydiaSubstrate and other libraries that helped in this area, please inform me.

推荐答案

我在 Swift 中成功地使用了方法 swizzling.这个例子展示了如何在 NSDictionary 上挂钩描述方法

I've succeed with method swizzling in Swift. This example shows how to hook description method on NSDictionary

我的实现:

extension NSDictionary {
     func myDescription() -> String!{
        println("Description hooked")
        return "Hooooked " + myDescription();
    }
}

混合代码:

func swizzleEmAll() {
        var dict:NSDictionary = ["SuperSecret": kSecValueRef]
        var method: Method = class_getInstanceMethod(object_getClass(dict), Selector.convertFromStringLiteral("description"))

        println(dict.description) // Check original description

        var swizzledMethod: Method = class_getInstanceMethod(object_getClass(dict), Selector.convertFromStringLiteral("myDescription"))
        method_exchangeImplementations(method, swizzledMethod)

        println(dict.description) //Check that swizzling works
    }

此代码适用于从 NSObject 继承的任何自定义 Swift 类(但不适用于不继承的类.)更多示例 - https://github.com/mbazaliy/MBSwizzler

Edited: This code will work for any custom Swift class that inherits from NSObject (but will not work for classes that don't.) More examples - https://github.com/mbazaliy/MBSwizzler

这篇关于Swift 函数调配/运行时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆