Skip to content

Commit

Permalink
Updated to Swift 2.
Browse files Browse the repository at this point in the history
  • Loading branch information
mickmaccallum committed Sep 19, 2015
1 parent cddb92a commit c4fc01a
Showing 1 changed file with 10 additions and 12 deletions.
22 changes: 10 additions & 12 deletions 2015-01-26-swift-objc-runtime.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,14 @@ extension UIViewController {
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)
.OBJC_ASSOCIATION_RETAIN_NONATOMIC
)
}
}
Expand All @@ -61,36 +62,36 @@ extension UIViewController {
static var token: dispatch_once_t = 0
}

// make sure this isn't a subclass
// 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)")
print("viewWillAppear: \(name)")
} else {
println("viewWillAppear: \(self)")
print("viewWillAppear: \(self)")
}
}
}
Expand All @@ -114,6 +115,3 @@ Instead of adding method swizzling via a class extension, simply add a method to


In closing, remember that tinkering with the Objective-C runtime should be much more of a last resort than a place to start. Modifying the frameworks that your code is based upon, as well as any third-party code you run, is a quick way to destabilize the whole stack. Tread softly!



0 comments on commit c4fc01a

Please sign in to comment.