Adding a getter makes using an underscore incorrect syntax

爷,独闯天下 提交于 2019-11-27 08:17:46

问题


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

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

- (NSString *)foo {
    return _foo;
}

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.

Thanks in advance!
-GoldDove


回答1:


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;

(or add the instance variable _foo explicitly.)

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.)




回答2:


This is because obj c creates the ivar for you along with a setter and getter whereas you used to have to synthesize the ivar yourself. If you manually create the setter AND getter, however, it assumes that you do not want the ivar and so you then have to synthesize it yourself.




回答3:


You seem to have two different names for your class. CustomClass and BlogPost. I suggest you make them both one or the other.



来源:https://stackoverflow.com/questions/18155881/adding-a-getter-makes-using-an-underscore-incorrect-syntax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!