Swift method_exchangeImplementations not working

quick code 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")

}

he writes:

function1 log

function1 log

///// my environment is a quick project, xcode7.2
It always works in a tag funtion1, so I think it exchanged unsuccessfully, these two methods are in the same class, does anyone know why?

+4
source share
1 answer

I get a response, add a "dynamic" keyword before the method name !!!
eg:

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

}

Reason:
Swift optimizes the code for calling direct memory addresses instead of finding the location of the method at runtime, as in Objective-C. so we need to say that running the code sees it as Objective-C code.

:
swizzling - , . swizzling, . Swift , Objective-C. swizzling Swift, :
1. . , , , Swift.
2. NSObject. swizzling ( ). , swizzling , NSObject , .
3. @objc swizzled. , , , Objective-C .

: 15 ,

+4

Source: https://habr.com/ru/post/1624923/


All Articles