首页 > 解决方案 > 将类别属性添加到确认协议的类

问题描述

我有一个生成器,它返回符合协议 A 的对象。我想为这些对象添加一个可能带有类别的属性,以便我可以做一些事情来满足我的目的,这显然不在协议中。

这是可行的吗?

标签: objective-cobjective-c-runtimeobjective-c-category

解决方案


这是可能的方法(基于 Objective-C 关联对象)。测试和工作。

假设我们有一些我们无法触及的类

    @interface SomeClass: NSObject
    @end

    @implementation SomeClass
    @end

然后可以通过以下方式注入一些新属性

    @interface SomeClass (VirtualProperty)
        @property (atomic) NSInteger virtualProperty;
        @property (nonatomic, readonly) NSInteger calculableProperty;
    @end

    static const char *kVirtualPropertyKey = "virtualProperty";

    @implementation SomeClass (VirtualProperty)
    @dynamic virtualProperty;

    - (NSInteger)calculableProperty {
        return self.virtualProperty * 2;
    }

    - (NSInteger)virtualProperty {
        return [(NSNumber *)objc_getAssociatedObject(self, 
            kVirtualPropertyKey) integerValue];
    }

    - (void)setVirtualProperty:(NSInteger)newValue {
        objc_setAssociatedObject(self, kVirtualPropertyKey, 
            @(newValue), OBJC_ASSOCIATION_RETAIN);
    }
    @end

用法:

    SomeClass *some = SomeClass.new;
    some.virtualProperty = 5;
    NSLog(@"Result: %lu", some.calculableProperty);

推荐阅读