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

查看:79
本文介绍了提供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;
}

错误:Use of undeclared identifier '_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天全站免登陆