Swift 関数のスウィズリング / ランタイム 質問する

Swift 関数のスウィズリング / ランタイム 質問する

Swift 以前は、Objective-C で を使用してクラス内のメソッドをスウィズルまたはフックしていました<objc/runtime.h>

Swift のランタイムを変更し、CydiaSubstrate やこの分野で役立つ他のライブラリなどの関数をフックするというトピックに関する情報をお持ちの方がいらっしゃいましたら、お知らせください。

ベストアンサー1

Swiftでメソッドスウィズリングに成功しました。この例では、NSDictionaryでdescriptionメソッドをフックする方法を示します。

私の実装:

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
    }

編集済み:このコードは、以下を継承するカスタムSwiftクラスであればどれでも動作します。NSオブジェクト(ただし、そうでないクラスでは機能しません。)その他の例 -https://github.com/mbazaliy/MBSwizzler

おすすめ記事