(Objective-C) 通过关联对象给分类添加成员变量

2022-06-12  本文已影响0人  布呐呐u
objc_setAssociatedObject(id _Nonnull object, const void * _Nonnull key,
                         id _Nullable value, objc_AssociationPolicy policy)
    OBJC_AVAILABLE(10.6, 3.1, 9.0, 1.0, 2.0);

objc_getAssociatedObject(id _Nonnull object, const void * _Nonnull key)
    OBJC_AVAILABLE(10.6, 3.1, 9.0, 1.0, 2.0);
// set method
- (void)setTestName:(NSString *)testName {
    objc_setAssociatedObject(self, @selector(testName), testName, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

// get method
- (NSString *)testName {
    return  objc_getAssociatedObject(self, _cmd);
}

// dealloc
- (void)dealloc {
    objc_removeAssociatedObjects(self);
}

objc_AssociationPolicy

上一篇 下一篇

猜你喜欢

热点阅读