I would like to make use of method swizzling, but am unable to get even simple examples to work for me. It is possible that I am misunderstanding what the concept is, but as far as I know it allows for method implementations to be swapped.
Given two methods, A and B, I would like to swap their implementations such that calling A would execute B instead. I came across a few examples of swizzling (example1 and example2). I created a new project with a class to test this.
class Swizzle: NSObject
{
func method()
{
print("A");
}
}
extension Swizzle
{
override class func initialize()
{
struct Static
{
static var token: dispatch_once_t = 0;
}
// make sure this isn't a subclass
if (self !== Swizzle.self)
{
return;
}
dispatch_once(&Static.token)
{
let originalSelector = Selector("method");
let swizzledSelector = Selector("methodExt");
let originalMethod = class_getInstanceMethod(self, originalSelector);
let swizzledMethod = class_getInstanceMethod(self, swizzledSelector);
print(method_getImplementation(originalMethod));
print(method_getImplementation(swizzledMethod));
let didAddMethod = class_addMethod(self, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod));
if didAddMethod
{
class_replaceMethod(self, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
}
else
{
method_exchangeImplementations(originalMethod, swizzledMethod);
}
print(method_getImplementation(originalMethod));
print(method_getImplementation(swizzledMethod));
}
}
func methodExt()
{
print("B");
}
}
I then try to execute it with
var s = Swizzle();
s.method();
The expected output is "B", but "A" is still being printed. As you can see from my code, I've included prints of each IMP
before and after the swizzle operation. These prints show that the exchange does take place, yet the output remains the same.
Output:
0x000000010251a920
0x000000010251ad40
0x000000010251ad40
0x000000010251a920
A
Is there anything I am missing when it comes to getting these changes to take effect?
PS. Currently using XCode 7.0.1