原理:由于swift扩展不能添加存储属性,所以考虑以计算属性获取另一对象的存储属性,该对象通过动态绑定给原对象
1,创建协议 包含中间对象,两个用于绑定的key
protocol AssociateObject {
var newInstance: AnyObject {get}
static var key:UnsafeRawPointer { get } //key不要用String类型
static var midKey:UnsafeRawPointer { get }
}
2,创建空类,用于生成中间对象
3,协议扩展,实现中间对象,并绑定
extension AssociateObject {
var newInstance: AnyObject {
guard let obj = objc_getAssociatedObject(self, Self.key) else {
let newInstance = NewClass.init()
objc_setAssociatedObject(self, Self.key, newInstance, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return newInstance
}
return obj as AnyObject
}
}
4,类的扩展遵守协议,并给出两个key,然后把需要的属性绑定给中间对象
extension UIView:AssociateObject {
static var key = UnsafeRawPointer("UIViewEx")
static var midKey: UnsafeRawPointer = UnsafeRawPointer("UIViewMidKey")
varviewName:String{
get{
guardletvalue =objc_getAssociatedObject(newInstance, &UIView.midKey) else{
returnString()
}
returnvalueas!String
}
set{
objc_setAssociatedObject(newInstance, &UIView.midKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}