iOS Setters 和 Getters 以及带下划线的属性名称

标签 ios objective-c

所以我有一个名为 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/

相关文章:

objective-c - 打开面板出现然后立即消失

ios - 从设备中删除本地 icloud 文件?

objective-c - Cocoa 绑定(bind)到 NSTableView 选择

ios - 为非方形UIImage添加边框

ios/objective-c/核心数据 : How to show relationship as property in NSManagedObjects

iphone - 访问无法修改的父类扩展中定义的 Obj-C 属性

ios - 正确设置 numberOfRowsInSection

ios - 滑动幻灯片并移动 imageView 位置

ios - 如何将 View Controller 覆盖在所有其他 Controller 之上

ios - ARC 在解除分配之前是否将其引用类型实例属性设置为 nil?