iOS Setters和Getters以及未标记的属性名称

所以我有一个名为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.
因此,当您获取/设置属性时,它实际上等于调用getter或seter.所以

self.description;

等于[自我描述].

self.description = myMutableString;

等于[self setDescription:myMutableString];

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

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

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

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...