Objective-C属性别名 [英] Objective-C property alias

查看:118
本文介绍了Objective-C属性别名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设ParentClass具有一个名为a的字符串属性:

Let's say that ParentClass has a string property called a:

@property (nonatomic, strong) NSString *a;

在子类ChildClass中,我希望属性bsuper.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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆