Associator
Associator is available through the dependency manager CocoaPods.
===================
Associator is a library built to manage Objc Associated Objects easily in a Swifty Manner.
Installation
To install the Warp iOS SDK via cocoapods, simply use the add this in your podfile and then run pod install
pod 'Associator'
How to use
To use Associator simply extend any class you would like to have any Associated Object with the Associator
protocol, and use the getters and setters methods in the .oa
namespace.
Example:
import Associator
extension UIButton: Associator {
private struct AssociatedKeys {
static var value: Int = 0
}
var value: Int {
get { return self.oa.get(&AssociatedKeys.value, defaultValue: AssociatedKeys.value) }
set { self.oa.set(newValue, forKey: &AssociatedKeys.value) }
}
}
Getting objects
You don't have to worry about type casting since the .get
method automatically infers the type for you.
The get method can also return a nullable value, you can do this by simply ommiting the defaultValue
parameter.
var string: String? {
get { return self.oa.get($someKeyHere) }
set { self.oa.set(newValue, forKey: $someKeyHere) }
}
Setting objects
Simply use the set(_ value: Any, forKey key: UnsafeRawPointer)
method. By default the association policy is set to use .retainNonAtomic
if you want to use a different association policy simply use the func set(_ value: Any, forKey key: UnsafeRawPointer, usingPolicy policy: AssociationPolicy)
Example:
self.oa.set(newValue, forKey: &AssociatedKeys.string)
self.oa.set(newValue, forKey: &AssociatedKeys.string, usingPolicy: .copyNonatomic)
self.oa.set(newValue, forKey: &AssociatedKeys.string, usingPolicy: .copy)