Skip to content

Instantly share code, notes, and snippets.

@haranicle
Last active February 10, 2016 06:50
Show Gist options
  • Save haranicle/15ee1a59ce7dbf15b23f to your computer and use it in GitHub Desktop.
Save haranicle/15ee1a59ce7dbf15b23f to your computer and use it in GitHub Desktop.
Swizzlingメモ #CodePiece
public override static func initialize() {
struct Static {
static var token: dispatch_once_t = 0
}
struct SwizzlingSelector {
let original:Selector
let swizzled:Selector
}
// make sure this isn't a subclass
if self !== SomeClass.self {
return
}
dispatch_once(&Static.token) {
let selectors = [
SwizzlingSelector(
original: Selector("collectionView:shouldSelectItemAtIndexPath:"),
swizzled: Selector("custom_collectionView:shouldSelectItemAtIndexPath:")
),
SwizzlingSelector(
original: Selector("viewDidLoad"),
swizzled: Selector("custom_viewDidLoad")
)
]
for selector in selectors {
let originalMethod = class_getInstanceMethod(self, selector.original)
let swizzledMethod = class_getInstanceMethod(self, selector.swizzled)
let didAddMethod = class_addMethod(self, selector.original, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod))
if didAddMethod {
class_replaceMethod(self, selector.swizzled, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod))
} else {
method_exchangeImplementations(originalMethod, swizzledMethod);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment