一.用property和synthesize分别进行成员变量的申明与实现
1.在xxx.h文件中用@property进行申明
// // Student.h // property // // Created by skythinking on 15/12/7. // Copyright © 2015年 skythinking. All rights reserved. // #import <Foundation/Foundation.h> @interface Student : NSObject { //默认是@protected 访问控制修饰符,此处用{}括起来,定义的是成员变量 int age; } //当编译器遇到@property时,会自动展开成getter和setter的声明 @property int age; //相当于下面这两句 //- (void)setAge:(int)newAge; //- (int) age; @end
// // Student.m // property // // Created by skythinking on 15/12/7. // Copyright © 2015年 skythinking. All rights reserved. // #import "Student.h" @implementation Student //@synthesize写在@implementation与@end之间 @synthesize age; //相当于下面的语句 //- (void)setAge:(int)newAge { // age = newAge; //} // //- (int)age { // return age; //} @end
// // main.m // property // // Created by skythinking on 15/12/7. // Copyright © 2015年 skythinking. All rights reserved. // #import <Foundation/Foundation.h> #import "Student.h" int main(int argc, const char * argv[]) { @autoreleasepool { Student *stu = [[Student alloc]init]; [stu setAge:10]; NSLog(@"age is %i",stu.age); } return 0; }
二.如果成员变量定义为_age,则按如下步骤操作
1.进行成员变量的定义与申明
// // Student.h // property // // Created by skythinking on 15/12/7. // Copyright © 2015年 skythinking. All rights reserved. // #import <Foundation/Foundation.h> @interface Student : NSObject { //默认是@protected 访问控制修饰符 int _age; } //当编译器遇到@property时,会自动展开成getter和setter的声明 @property int age; //相当于下面这两句 //- (void)setAge:(int)newAge; //- (int) age; @end
// // Student.m // property // // Created by skythinking on 15/12/7. // Copyright © 2015年 skythinking. All rights reserved. // #import "Student.h" @implementation Student //age=_age代表getter和setter回去访问_age这个成员变量 @synthesize age=_age; //相当于下面这两句 //- (void)setAge:(int)newAge { // _age = newAge; //} //- (int)age { // return _age; //} @end
// // main.m // property // // Created by skythinking on 15/12/7. // Copyright © 2015年 skythinking. All rights reserved. // #import <Foundation/Foundation.h> #import "Student.h" int main(int argc, const char * argv[]) { @autoreleasepool { Student *stu = [[Student alloc]init]; [stu setAge:10]; NSLog(@"age is %i",stu.age); } return 0; }
补充:1.生成private成员变量
// // Student.h // property // // Created by skythinking on 15/12/7. // Copyright © 2015年 skythinking. All rights reserved. // #import <Foundation/Foundation.h> @interface Student : NSObject //下面定义的是私有成员变量 @private //当编译器遇到@property时,会自动展开成getter和setter的声明 @property int age; //此句编译器会默认生成_age变量,所以在.m文件中需要这样赋值_age = xxx //相当于下面这两句 //- (void)setAge:(int)newAge; //- (int) age; @end
// // Student.h // property // // Created by skythinking on 15/12/7. // Copyright © 2015年 skythinking. All rights reserved. // #import <Foundation/Foundation.h> @interface Student : NSObject { //默认是@protected 访问控制修饰符 int age; } //当编译器遇到@property时,会自动展开成getter和setter的声明 @property int age; //相当于下面这两句 //- (void)setAge:(int)newAge; //- (int) age; @end