Created
September 26, 2017 20:32
-
-
Save bruno-rocha-movile/8f5178047c4e99c4740148dc51fc97ba to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// Swizzler.swift | |
// Fenrir | |
// | |
// Created by Bruno Rocha on 2/3/17. | |
// Copyright © 2017 Bruno Rocha. All rights reserved. | |
// | |
import UIKit | |
extension Fenrir { | |
@objc func emptyMethod() {} | |
func swizzle(method originalSelector: Selector, fromClass `class`: AnyClass , with swizzledSelector: Selector, fromClass swizzledClass: AnyClass, token: String, dontForceAdd: Bool = false) { | |
DispatchQueue.once(token: token) { | |
var originalMethod: Method! { | |
return class_getInstanceMethod(`class`, originalSelector) | |
} | |
var swizzledMethod: Method! { | |
return class_getInstanceMethod(`class`, swizzledSelector) | |
} | |
if originalMethod == nil { | |
if dontForceAdd { | |
return | |
} | |
let emptyMethod = class_getInstanceMethod(Fenrir.self, #selector(Fenrir.emptyMethod)) | |
class_addMethod(`class`, originalSelector, method_getImplementation(emptyMethod), method_getTypeEncoding(emptyMethod)) | |
} | |
if swizzledMethod == nil { | |
let trueSwizzledMethod = class_getInstanceMethod(swizzledClass, swizzledSelector) | |
class_addMethod(`class`, swizzledSelector, method_getImplementation(trueSwizzledMethod), method_getTypeEncoding(trueSwizzledMethod)) | |
} | |
method_exchangeImplementations(originalMethod, swizzledMethod) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment