Created
October 16, 2018 14:25
-
-
Save nanoxd/b4f01678a799f757ee34bc5e3ab42e12 to your computer and use it in GitHub Desktop.
[NSObject+AssociatedObject] Wrapper around associated objects #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
public enum AssociationPolicy { | |
case assign | |
case retain | |
case copy | |
case retainNonatomic | |
case copyNonatomic | |
fileprivate var policy: objc_AssociationPolicy { | |
switch self { | |
case .assign: return .OBJC_ASSOCIATION_ASSIGN | |
case .retain: return .OBJC_ASSOCIATION_RETAIN | |
case .copy: return .OBJC_ASSOCIATION_COPY | |
case .retainNonatomic: return .OBJC_ASSOCIATION_RETAIN_NONATOMIC | |
case .copyNonatomic: return .OBJC_ASSOCIATION_COPY_NONATOMIC | |
} | |
} | |
} | |
public extension NSObjectProtocol { | |
public func setAssociatedObject(_ object: Any?, forKey key: UnsafeRawPointer, policy: AssociationPolicy = .retain) { | |
objc_setAssociatedObject(self, key, object, policy.policy) | |
} | |
public func associatedObject<T>(for key: UnsafeRawPointer) -> T? { | |
return objc_getAssociatedObject(self, key) as? T | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment