利用运行时给分类动态添加成员变量

一、新建一个分类

二、加入属性

三、引入objc/runtime头文件

四、制定一个字符串

五、实现get,set方法

在网上还看到有人用了宏,宏是这样的,使用是这样的。

#define uxy_property_as_associated_strong( __type, __name) 
        @property (nonatomic, strong, setter=set__##__name:, getter=__##__name) __type __name;

#define uxy_property_def_associated_strong( __type, __name) 
        - (__type)__##__name   
        { return [self uxy_getAssociatedObjectForKey:#__name]; }   
        - (void)set__##__name:(id)__##__name   
        { [self uxy_retainAssociatedObject:__##__name forKey:#__name]; }

是这样使用的

@interface UINavigationBar (XY)
uxy_property_as_associated_strong(id, test2);
@end

@implementation UINavigationBar (XY)
uxy_property_def_associated_strong(id, test2)
@end

{
    self.test2 = @"a";
    id c = self.test2;
    NSLog(@"%@", c);
}
原文地址:https://www.cnblogs.com/songxing10000/p/4640557.html