所以我有一个名为 description 的 NSString 属性,定义如下:
@property (strong, nonatomic) NSMutableString *description;
当我定义 getter 时,我可以将其称为 _description,如下所示:
- (NSString *)description
{
return _description;
}
但是,当我定义一个setter时,如下:
-(void)setDescription:(NSMutableString *)description
{
self.description = description;
}
它打破了上述 getter(未声明的标识符)中的 _description。我知道我可以只使用 self.description,但为什么会这样?
最佳答案
@borrrden 的回答很好。我只想添加一些细节。
属性实际上只是语法糖。所以当你像你一样声明一个属性时:
@property (strong, nonatomic) NSMutableString *description;
它是自动合成的。含义:如果您不提供自己的 getter + setter(请参阅 borrrden 的回答),则会创建一个实例变量(默认情况下它的名称为“underscore + propertyName”)。而getter + setter是根据你提供的属性描述合成的(strong, nonatomic)。 所以当你获取/设置属性的时候,其实就等于调用了getter或者seter。所以
self.description;
等于[self description]
。
和
self.description = myMutableString;
等于[self setDescription: myMutableString];
因此,当您像以前那样定义一个 setter 时:
-(void)setDescription:(NSMutableString *)description
{
self.description = description;
}
它会导致无限循环,因为 self.description = description;
调用 [self setDescription:description];
。
关于iOS Setters 和 Getters 以及带下划线的属性名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17017073/