Created
July 27, 2016 07:44
-
-
Save verma-manish58/6c756f09362c4e7eb54b0a6d7e5d4a57 to your computer and use it in GitHub Desktop.
This file contains 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 NSObject { | |
/** | |
* ASSOCIATED - OBJECTS | |
*/ | |
public func associate(value: AnyObject, withKey: String) { | |
objc_setAssociatedObject(self, withKey, value, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) | |
} | |
public func getAssociatedValue(key: String) -> AnyObject { | |
return objc_getAssociatedObject(self, key) | |
} | |
} |
This file contains 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 NSObject { | |
struct Static { | |
static var onceToken: dispatch_once_t = 0 | |
} | |
/** | |
Method Swizzling | |
- parameter className: name of the class for which swizzling needs to happen | |
- parameter originalSelector: originalSelector: method which is already present in the class | |
- parameter swizzledSelector: swizzledSelector: new method which will be swizzled with the originSelector | |
*/ | |
public func swizzleInstanceMethod(className: AnyClass, originalSelector: Selector, swizzledSelector: Selector) { | |
dispatch_once (&Static.onceToken) { | |
let originalMethod = class_getInstanceMethod(className, originalSelector) | |
let swizzledMethod = class_getInstanceMethod(className, swizzledSelector) | |
let didAddMethod = class_addMethod(className, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod)) | |
if didAddMethod { | |
class_replaceMethod(className, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod)) | |
}else { | |
method_exchangeImplementations(originalMethod, swizzledMethod) | |
} | |
} | |
} | |
public func swizzleClassMethod(className: AnyClass, originalSelector: Selector, swizzledSelector: Selector) { | |
dispatch_once (&Static.onceToken) { | |
let originalMethod = class_getClassMethod(className, originalSelector) | |
let swizzledMethod = class_getClassMethod(className, swizzledSelector) | |
let didAddMethod = class_addMethod(className, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod)) | |
if didAddMethod { | |
class_replaceMethod(className, swizzledSelector, 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