如何给iOS分类动态添加属性

给分类扩展属性

  • 创建Person 这个类 并且为Person这个类增加分类
Paste_Image.png
  • 为Person这个类扩充属性testName
#import "Person.h"
@interface Person (Extension)
/**
 *  名字
 */
@property (nonatomic, copy) NSString *testName;
@end
  • 接下来创建一个Person对象并且开始使用这个属性
#import "ViewController.h"
#import "Person.h"
#import "Person+Extension.h"

@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
    [super viewDidLoad];

    Person *p = [[Person alloc]init];
    p.testName = @"jack";
}
  • 运行发现报错 ,由此可以推断分类中的属性 系统没有为你实现set 方法及get方法
Paste_Image.png

解决办法 自己实现这个属性set 方法及get方法

#import "Person+Extension.h"
#import <objc/runtime.h>

static NSString *testNameKey = @"testNameKey";
static NSString *testAgeKey = @"testAgeKey";

@implementation Person (Extension)

@dynamic testName;
@dynamic testAge;

-(void)setTestName:(NSString *)testName
{
    objc_setAssociatedObject(self, &testNameKey, testName, OBJC_ASSOCIATION_RETAIN);
}
-(NSString *)testName{
  return objc_getAssociatedObject(self, &testNameKey);
}

-(void)setTestAge:(int)testAge{

    objc_setAssociatedObject(self, &testAgeKey, @(testAge), OBJC_ASSOCIATION_RETAIN);
}

-(int)testAge{

    return [objc_getAssociatedObject(self, &testAgeKey) intValue];
}

@end
  • 接下来回到控制器看是不是已经扩展ok
Paste_Image.png
  • OK
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容