objective-c - 将类别属性添加到确认协议的类
问题描述
我有一个生成器,它返回符合协议 A 的对象。我想为这些对象添加一个可能带有类别的属性,以便我可以做一些事情来满足我的目的,这显然不在协议中。
这是可行的吗?
解决方案
这是可能的方法(基于 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);
推荐阅读
- node.js - 无法使用 fs 读取 .txt 的内容
- java - JavaFX ChoiceBox 不通过 setValue() 显示值
- flutter - Flutter / Dart:启动应用程序时如何在第一个选项卡上加载数据?
- kubernetes - 在 Kubernetes cronjob 中指定角色
- r - 条件匹配
- vba - 如何在access中的图片框上显示pdf
- c# - 使用 C# 将 Null 插入数据库
- android - Flutter:Google Speech-To-Text API 总是返回 null
- javascript - 使用js设置css变量时转义的url
- azure-devops - 如何以编程方式创建 Azure DevOps 组织