class Person : NSObject {
}
extension Person {
private static var AGE_KEY: Bool = false
// 这里为什么用bool类型,因为省内存,因为只是用来作为记录地址的
private static var WEIGHT_KEY:Bool = false
var age:Int {
get {
objc_getAssociatedObject(self, &Self.AGE_KEY) as! Int
}
set {
objc_setAssociatedObject(self, &Self.AGE_KEY, newValue, .OBJC_ASSOCIATION_ASSIGN)
}
}
var weight:Int {
get {
objc_getAssociatedObject(self, &Self.WEIGHT_KEY) as! Int
}
set {
objc_setAssociatedObject(self, &Self.WEIGHT_KEY, newValue, .OBJC_ASSOCIATION_ASSIGN)
}
}
}
简单点讲,就是类似OC的分类里面,扩展了一个属性,一般原则上这样是不允许的,但是通过关联对象的这种方法,是可以的