为什么在提供 getter 和 setter 时需要编写 @synthesize? [英] Why do I need to write @synthesize when I provide getter and setter?

查看:24
本文介绍了为什么在提供 getter 和 setter 时需要编写 @synthesize?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以属性的自动合成很棒.但是,当您同时提供 getter 和 setter 时,会出现错误.

So the auto synthesize of properties is awesome. However, when you provide both a getter and a setter, you get an error.

@property (strong, nonatomic) NSArray *testArray;

- (NSArray *)testArray {
    return _testArray;
}

- (void)setTestArray:(NSArray *)testArray {
    _testArray = testArray;
}

错误:使用未声明的标识符_testArray".

添加@synthesize testArray = _testArray; 解决问题.我只是想知道这是为什么?

Adding @synthesize testArray = _testArray; solves the problem. I am just wondering why this is?

推荐答案

当您同时提供 getter 和 setter 时,通常根本不需要实例变量,即当您只是转发这些消息或将数据存储在其他地方.

When you provide both getter and setter, there is often just no need for an instance variable at all, i.e. when you just forward those messages or store data in other places.

一旦其中一个缺失,就需要 ivar 来合成该功能.

As soon as one of them is missing, the ivar is needed to synthesize that functionality.

如果我没记错的话,对于只读属性,模拟假设也成立.

If I remember correctly, for readonly properties the analogue assumption holds as well.

这篇关于为什么在提供 getter 和 setter 时需要编写 @synthesize?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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