Created
August 13, 2015 17:16
-
-
Save hsavit1/53add4601f1323cd33f1 to your computer and use it in GitHub Desktop.
Associated Objects and Method Swizzling in Swift
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
extension UIViewController { | |
private struct AssociatedKeys { | |
static var DescriptiveName = "nsh_DescriptiveName" | |
} | |
var descriptiveName: String? { | |
get { | |
return objc_getAssociatedObject(self, &AssociatedKeys.DescriptiveName) as? String | |
} | |
set { | |
if let newValue = newValue { | |
objc_setAssociatedObject( | |
self, | |
&AssociatedKeys.DescriptiveName, | |
newValue as NSString?, | |
UInt(OBJC_ASSOCIATION_RETAIN_NONATOMIC) | |
) | |
} | |
} | |
} | |
} |
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
extension UIViewController { | |
public override class func initialize() { | |
struct Static { | |
static var token: dispatch_once_t = 0 | |
} | |
// make sure this isn't a subclass | |
if self !== UIViewController.self { | |
return | |
} | |
dispatch_once(&Static.token) { | |
let originalSelector = Selector("viewWillAppear:") | |
let swizzledSelector = Selector("nsh_viewWillAppear:") | |
let originalMethod = class_getInstanceMethod(self, originalSelector) | |
let swizzledMethod = class_getInstanceMethod(self, swizzledSelector) | |
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); | |
} | |
} | |
} | |
// MARK: - Method Swizzling | |
func nsh_viewWillAppear(animated: Bool) { | |
self.nsh_viewWillAppear(animated) | |
if let name = self.descriptiveName { | |
println("viewWillAppear: \(name)") | |
} else { | |
println("viewWillAppear: \(self)") | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment