Objective c 目标C getter方法不适用于属性
我在玩objective C。这是我写的一个类的代码,算术。h:Objective c 目标C getter方法不适用于属性,objective-c,class,properties,Objective C,Class,Properties,我在玩objective C。这是我写的一个类的代码,算术。h: #import <Foundation/Foundation.h> @interface arithmetic : NSObject @property int cur; -(id)initWithNumber:(int)number; @end @implementation arithmetic @synthesize cur; - (instancetype)init { self = [
#import <Foundation/Foundation.h>
@interface arithmetic : NSObject
@property int cur;
-(id)initWithNumber:(int)number;
@end
@implementation arithmetic
@synthesize cur;
- (instancetype)init
{
self = [super init];
if (self) {
NSLog(@"Yo, all works :D ");
}
return self;
}
-(id)initWithNumber:(int)num{
self = [super init];
if(self){
[self setCur:8] ;
}
return self;
}
@end
前两行可以工作。但最后一行说
算术没有可见接口声明选择器“getCur”
问题是什么?这是因为当您在@implementation中这样声明时:
@synthesize cur;
它将创建getter
-(int)cur {
return _cur;
}
它还将创建一个setter
-(void)setCur:(int)newCur {
_cur = newCur;
}
总之,Objective-C getter/setter分别具有propery/setProperty模式,这与使用getProperty/setProperty的Java不同
而Objective-C getter/setter是通过点(.)符号访问的。比如说
int x = obj.cur;
obj.cur = 100;
getter只是
cur
。就是这样吗?我认为有一套和一套是有意义的。医生说。用于设置值的方法(setter方法)以单词“set”开头,然后使用大写的属性名称。名为firstName的属性的setter方法将被称为setFirstName:是的,就是它。关于setter的命名方式,您是对的,只是假设getter是错的。他们可以选择任何一种方式,也许是符合点语法的朴素名称帮助了选择。
int x = obj.cur;
obj.cur = 100;