// Associated Object// 动态添加成员变量。 直接添加成员变量是不允许的,利用 OC 的运行时和 KVC 特性,我们可以在运行时想一个对象添加值存储。// 利用 property 配合 Associated Object // 添加 和 获得的方法/*func objc_getAssociatedObject(object: AnyObject!, key: UnsafePointer) -> AnyObject!func objc_setAssociatedObject(object: AnyObject!, key: UnsafePointer,
value: AnyObject!,
policy: objc_AssociationPolicy)
*/
class MyClass{ }
private var titleKey: Void?
extension MyClass {
var title : String? {
get{
return objc_getAssociatedObject(self, &titleKey) as? String
}
set{
objc_setAssociatedObject(self, &titleKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
// 测试
func printTitle(_ input: MyClass){
if let title = input.title {
print("Title: \(title)")
} else {
print("没有设置")
}
}
let a = MyClass()
print(a)
a.title = "Swifter.tips"
print(a.title) // Optional("Swifter.tips")