Skip to content

如何给分类添加属性?关联对象以什么形式进行存储? #30

@tbfungeek

Description

@tbfungeek

在分类中添加属性声明的时候编译器会为这个属性添加getter/setter方法,但是没有添加实例对象,所以必须借助关联对象为这个属性提供数据存储的地方。

下面是通过分类为某个类添加属性的代码:

NS_ASSUME_NONNULL_BEGIN
@interface IDLObject (IDLAddition)
@property(nonatomic, strong , readwrite) NSString *idl_customProperty;
@end
NS_ASSUME_NONNULL_END
//objc
#import <objc/runtime.h>
@implementation IDLObject (IDLAddition)
- (void)setIdl_customProperty:(NSString *)idl_customProperty {
    objc_setAssociatedObject(self, @selector(idl_customProperty), idl_customProperty, OBJC_ASSOCIATION_RETAIN);
}

- (NSString *)idl_customProperty {
    return objc_getAssociatedObject(self, @selector(idl_customProperty));
}
@end

关联对象以什么形式进行存储 见关联部分的解析

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions