swift method_exchangeImplementations not work

安稳与你 提交于 2020-02-28 04:58:25

问题


swift code is below:

func swizzleMethod()
{
    let method:Method = class_getInstanceMethod(object_getClass(self), Selector("function1"))

    self.function1()
    let swizzledMethod:Method = class_getInstanceMethod(object_getClass(self), Selector("function2"))

    method_exchangeImplementations(method, swizzledMethod)

    self.function1()


}

func function1()
{
    print("function1 log")
}
func function2()
{
    print("function2 log")

}

it logs:

function1 log

function1 log

///// my environment is swift based project, xcode7.2
This always run into the funtion1 method body, so I think it exchanged failed, this two method is in the same class, anyone know why?


回答1:


I get the answer, add "dynamic" keyword in front of method name!!!
like this:

dynamic  func function1()
{
    print("function1 log")
}
dynamic func function2()
{
    print("function2 log")

}

Reason:
Swift optimizes code to call direct memory addresses instead of looking up the method location at runtime as in Objective-C. so we need tell the code run treat it as Objective-C code.

Answer Detail:
Method swizzling is a technique that substitutes one method implementation for another. If you're not familiar with swizzling, check out this blog post. Swift optimizes code to call direct memory addresses instead of looking up the method location at runtime as in Objective-C. So by default swizzling doesn’t work in Swift classes unless we:
1. Disable this optimization with the dynamic keyword. This is the preferred choice, and the choice that makes the most sense if the codebase is entirely in Swift.
2. Extend NSObject. Never do this only for method swizzling (use dynamic instead). It’s useful to know that method swizzling will work in already existing classes that have NSObject as their base class, but we're better off selectively choosing methods with dynamic .
3. Use the @objc annotation on the method being swizzled. This is appropriate if the method we would like to swizzle also needs to be exposed to Objective-C code at the same time.

thanks to the article: 15 Tips to Become a Better Swift Developer



来源:https://stackoverflow.com/questions/34871893/swift-method-exchangeimplementations-not-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!