Objective-C属性别名 [英] Objective-C property alias
问题描述
假设ParentClass
具有一个名为a
的字符串属性:
Let's say that ParentClass
has a string property called a
:
@property (nonatomic, strong) NSString *a;
在子类ChildClass
中,我希望属性b
是super.a
的别名.含义b
本身并不真正拥有任何值,它只是指向a
.
如果a
的值发生变化,则应将其反映在b
中,反之亦然.
In a subclass ChildClass
, I want the property b
to be an alias for super.a
. Meaning b
does not really hold any value in itself, it just points to a
.
If the value of a
changes, then it should be reflected in b
, and vice-versa.
在Objective-C中最干净的方法是什么.
What the the cleanest way to achieve this in Objective-C.
推荐答案
您不能这样做别名.但是,属性只是方法实现的捷径.子类继承其超类的(可见)属性,因此您可以执行以下操作:
You can't do aliases, as such. However, properties are just short-hand for method implementations. Subclasses inherit (visible) properties of their superclass(es), so you can do something like the following:
- (void)setB:(NSString *)b {
self.a = b;
}
- (NSString *)b {
return self.a;
}
如果a
对子类不可见,则必须执行以下操作:
If a
is not visible to the subclass, you have to do something like this:
- (void)setB:(NSString *)b {
[self setValue:b forKey:@"a"];
}
- (NSString *)b {
return [self valueForKey:@"a"];
}
之所以可行,是因为在运行时没有类型检查,因此,如果该属性存在(具有getter和setter的标准名称),您仍然可以使用KVC对其进行操作.
This works because there's no type-checking at runtime, so if the property exists (with the standard names for the getter and setter), you can still use KVC to manipulate it.
这篇关于Objective-C属性别名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!