添加 getter 会使使用下划线的语法不正确 [英] Adding a getter makes using an underscore incorrect syntax

查看:22
本文介绍了添加 getter 会使使用下划线的语法不正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有以下标题的类:

I have a class with the following header:

#import <Foundation/Foundation.h>

@interface CustomClass : NSObject

@property (strong, nonatomic) NSString *foo;

@end

使用以下未显示任何错误的实现:

With the following implementation that does not show any errors:

#import "CustomClass.h"

@implementation CustomClass

- (void) setFoo:(NSString *)foo {
    _foo = foo;
}

@end

作为一个完整的Objective-C初学者,当我在实现中添加以下方法时,我感到很困惑:

Being a complete beginner to Objective-C, I am baffled when I add the following method to the implementation:

- (NSString *)foo {
    return _foo;
}

因为现在方法 use of undeclared identifier 'title' 中存在错误,它建议我将 _foo 更改为 foo.不光是在新增的方法里这么说,在之前的setter方法里也这么说.我试图查找情况,但没有找到满意的答复.相关问题谈论@synthesize,但我有读到没有必要,所以我不确定是什么问题.

because now there is an error in the method use of undeclared identifier 'title' and it recommends that I change _foo to foo. Not only does it say that in the newly added method, it also says it in the previous setter method. I have tried to look up the situation and I have not found a satisfactory response. Related questions talk about @synthesize, but I have read that it is not necessary, so I am not sure what the problem is.

提前致谢!
-GoldDove

Thanks in advance!
-GoldDove

推荐答案

一个属性没有自动合成如果您为该属性实现 setter 和 getter 方法,那么您必须明确地合成它:

A property is not automatically synthesized if you implement both setter and getter method for that property, so you have to synthesize it explicitly:

@synthesize foo = _foo;

(或显式添加实例变量_foo.)

(or add the instance variable _foo explicitly.)

同样适用于为只读属性实现 getter 方法的情况.

The same applies if you implement the getter method for a read-only property.

(如果你为一个属性实现了所有必要的访问器方法,那么编译器不再假设此属性必须由实例备份变量.)

(If you implement all necessary accessor methods for a property then the compiler does not assume anymore that this property is necessarily backed up by an instance variable.)

这篇关于添加 getter 会使使用下划线的语法不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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