添加getter会使用下划线不正确的语法

gol*_*ove 3 xcode properties objective-c getter-setter synthesize

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

#import <Foundation/Foundation.h>

@interface CustomClass : NSObject

@property (strong, nonatomic) NSString *foo;

@end
Run Code Online (Sandbox Code Playgroud)

使用以下实现不会显示任何错误:

#import "CustomClass.h"

@implementation CustomClass

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

@end
Run Code Online (Sandbox Code Playgroud)

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

- (NSString *)foo {
    return _foo;
}
Run Code Online (Sandbox Code Playgroud)

因为现在方法中存在错误use of undeclared identifier 'title',它建议我更改_foofoo.它不仅表示在新添加的方法中,它还在之前的setter方法中说明了它.我试图查看情况,但我没有找到满意的答复.相关问题请谈@synthesize,但我已经读到没有必要,所以我不确定问题是什么.

提前致谢!
-GoldDove

Mar*_*n R 6

一个属性,如果你执行不自动合成为财产setter和getter方法,所以你必须明确地合成它:

@synthesize foo = _foo;
Run Code Online (Sandbox Code Playgroud)

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

如果为只读属性实现getter方法,则同样适用.

(如果为属性实现所有必需的访问器方法,则编译器不再假设此属性必须由实例变量备份.)