Last active
February 10, 2016 06:50
-
-
Save haranicle/15ee1a59ce7dbf15b23f to your computer and use it in GitHub Desktop.
Swizzlingメモ #CodePiece
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
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