iOS Category/分类添加成员变量
2021-06-18 本文已影响0人
iOS刘耀宗
项目 Demo 下载
注意: 分类是不能直接添加成员变量到分类中的,但是可以通过关联对象添加成员变量
关联对象主要使用下面的 api
添加关联对象:
//关联对象
//object: 需要关联的对象
//key: 关联的 key 用来取值
//value: 关联的值
/*policy: 关联策略, 就是给属性增加 copy,strong,assgin. 一样的用法.具体对应请参考图1
typedef OBJC_ENUM(uintptr_t, objc_AssociationPolicy) {
OBJC_ASSOCIATION_ASSIGN = 0, /**< Specifies a weak reference to the associated object. */
OBJC_ASSOCIATION_RETAIN_NONATOMIC = 1, /**< Specifies a strong reference to the associated object.
* The association is not made atomically. */
OBJC_ASSOCIATION_COPY_NONATOMIC = 3, /**< Specifies that the associated object is copied.
* The association is not made atomically. */
OBJC_ASSOCIATION_RETAIN = 01401, /**< Specifies a strong reference to the associated object.
* The association is made atomically. */
OBJC_ASSOCIATION_COPY = 01403 /**< Specifies that the associated object is copied.
* The association is made atomically. */
};
*/
void objc_setAssociatedObject(id object, const void * key,
id value, objc_AssociationPolicy policy)
//获得关联对象
//object :关联的对象
//key: 关联的key
id objc_getAssociatedObject(id object, const void * key)
//移除所有的关联对象
//object: 关联的对象
void objc_removeAssociatedObjects(id object)
图 1:

关联 key 的常规用法
static void *MyKey = &MyKey;
objc_setAssociatedObject(obj, MyKey, value, OBJC_ASSOCIATION_RETAIN_NONATOMIC)
objc_getAssociatedObject(obj, MyKey)
static char MyKey;
objc_setAssociatedObject(obj, &MyKey, value, OBJC_ASSOCIATION_RETAIN_NONATOMIC)
objc_getAssociatedObject(obj, &MyKey)
使用属性名作为key
objc_setAssociatedObject(obj, @"property", value, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
objc_getAssociatedObject(obj, @"property");
使用get方法的@selecor作为key
objc_setAssociatedObject(obj, @selector(getter), value, OBJC_ASSOCIATION_RETAIN_NONATOMIC)
objc_getAssociatedObject(obj, @selector(getter))
如何使用
import UIKit
class Person: NSObject {
}
extension Person {
var name: String {
get {
return objc_getAssociatedObject(self, "name") as! String
}
set {
objc_setAssociatedObject(self, "name", newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_COPY_NONATOMIC)
}
}
}
let model = Person()
model.name = "测试"
print("name= \(model.name)")