ios中object-c语言的@property和@synthesize关键字是用来省略类变量的get与set的方法的,我们之前定义一个Student学生类,需要在.h文件中申明变量的get与set方法,并且还要在.m实现文件中实现.h文件中申明的方法,这样的代码看起来很冗余,之前的代码如下。
Student.h的申明文件:
#import <Foundation/Foundation.h>
@interface Student : NSObject{
int age;
}
//get方法申明
-(int)age;
//set方法申明
-(void)setAge : (int)newAge;
@endStudent.m中实现文件的代码:
#import "Student.h"
@implementation Student
//get方法实现
-(int)age{
return age;
}
//set方法实现
-(void)setAge:(int)newAge{
age = newAge;
}
@end以上的代码如果属性很多的话,会有很多不必要的代码,这样就会影响我们的开发效率,如果使用@property和@synthesize这两个关键字的话,会节约不少时间,@property是方法的申明,@synthesize是方法的实现关键字,以上的代码可以直接简写成以下的形式。
简写后的Student.h的申明文件:
#import <Foundation/Foundation.h> @interface Student : NSObject //有了这个关键字,oc会自动加入age同名的变量,就不需要再添加类变量了。 @property int age; @end
简写后的Student.m实现文件的代码:
#import "Student.h" @implementation Student //这一个不需要也可以,因为xcode会自动帮你加上实现方法 @synthesize age; @end
请注意,在object-c中,@property和@synthesize只能简写类变量的get和set方法申明和实现,如果get和set方法需要自定义,就不能用这个关键字。