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

查看:101
本文介绍了添加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

推荐答案

属性不会自动合成 如果您为该属性实现 better 和setter方法,那么您必须 明确地将其合成:

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天全站免登陆