iOS Setters和Getters以及未标记的属性名称 [英] iOS Setters and Getters and Underscored Property Names

查看:78
本文介绍了iOS Setters和Getters以及未标记的属性名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个名为description的NSString属性,定义如下:

So I have a NSString property named description, defined as follows:

@property (strong, nonatomic) NSMutableString *description;

我在定义getter时可以将它称为_description,如下所示:

I'm able to refer to it as _description when I define the getter, as follows:

- (NSString *)description
{
    return _description;
}

但是,当我定义一个setter时,如下所示:

However, when I define a setter, as follows:

-(void)setDescription:(NSMutableString *)description
{
    self.description = description;
}

它从前面提到的getter(未声明的标识符)中断了_description。我知道我可能只是使用self.description,但为什么会这样呢?

It breaks _description from the aforementioned getter (undeclared identifier). I know I can probably just use self.description instead, but why does this happen?

推荐答案

@borrrden的答案非常好。我只是想补充一些细节。

@borrrden 's answer is very good. I just want to add some details.

属性实际上只是语法糖。因此,当您声明属性时:

Properties are actually just syntax sugar. So when you declare a property like you did:

@property (strong, nonatomic) NSMutableString *description;

它是自动合成的。含义:如果你不提供自己的getter + setter(参见borrrden的答案),就会创建一个实例变量(默认情况下它的名称为underscore + propertyName)。 getter + setter根据您提供的属性描述(强大,非原子)合成。
所以当你得到/设置属性时,它实际上等于调用getter或seter。所以

It is automatically synthesized. What it means: if you don't provide your own getter + setter (see borrrden's answer), an instance variable is created (by default it has name "underscore + propertyName"). And getter + setter are synthesized according to the property description that you provide (strong, nonatomic). So when you get/set the property, it is actually equal to calling the getter or the seter. So

self.description;

等于 [自我描述]

self.description = myMutableString;

等于 [self setDescription:myMutableString];

因此,当你像你一样定义一个setter:

Therefore when you define a setter like you did:

-(void)setDescription:(NSMutableString *)description
{
    self.description = description;
}

它会导致无限循环,因为 self.description = description; 调用 [self setDescription:description];

It causes an infinite loop, since self.description = description; calls [self setDescription:description];.

这篇关于iOS Setters和Getters以及未标记的属性名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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