OC语言学习 (三) 成员变量get/set方法和“.”语法,@proterty和@synthesize关键字
来源:互联网 发布:詹姆斯数据 编辑:程序博客网 时间:2024/05/05 19:17
Person.h
- #ifndef oc_Person_h
- #define oc_Person_h
- @interface Person : NSObject
- {
- int age;
- @protected
- float height;
- }
- - (int) age; //get方法
- - (void) setAge:(int)pAge; //set方法
- @end
- #endif
Person.m
- #import <Foundation/Foundation.h>
- #import "Person.h"
- @implementation Person
- - (int) age
- {
- return age;
- }
- - (void) setAge:(int)pAge
- {
- age = pAge;
- }
- @end
main.m
- int main()
- {
- Person* per = [[Person alloc] init];
- int age = [per age]; //调用get方法
- [per setAge:16]; //调用set方法
- //使用“.” 来调用get/set 使用的都是原始变量名,这就要求变量的get、set都符合约定
- int age2 = per.age; //get
- per.age = 17; //set
- return 0;
- }
每次这样写get/set方法,很麻烦,OC有一个自动化的方法,即使用@proterty和@synthesize关键字
Person.h
- #ifndef oc_Person_h
- #define oc_Person_h
- @interface Person : NSObject
- {
- int age;
- @protected
- // float height;
- }
- //- (int) age;
- //- (void) setAge:(int)pAge;
- @property int age; //编译器自动解释成 int age的get/set方法 的声明。
- //@property int age = _age;//如果没有指定成员变量名,实现中默认访问的同名的成员变量age
- @property float height; //如果height没有声明,而用在这里, 也会自动生成以height为标准名的 get/set方法
- @end
- #endif
Person.m
- #import <Foundation/Foundation.h>
- #import "Person.h"
- @implementation Person
- //- (int) age
- //{
- // return age;
- //}
- //
- //- (void) setAge:(int)pAge
- //{
- // age = pAge;
- //}
- @synthesize age; //编译器自动解释成 age的get、set方法实现。 在xcode4.5之后可以不写这句话
- @synthesize height = _height; //如果_height不存在,会生成一个私有的_height变量
- @end
0 0
- OC语言学习 (三) 成员变量get/set方法和“.”语法,@proterty和@synthesize关键字
- OC语言学习 (三) 成员变量get/set方法和“.”语法,@proterty和@synthesize关键字
- OC基础(三)get/set/. @proterty和@synthesize关键字等使用
- 黑马程序员——OC语言学习——Xcode开发初始化、点语法、成员变量作用域、关键字@property和@synthesize
- 黑马程序员-用点语法,@property关键字和@synthesize关键字优化set和get方法
- OC学习之属性关键字以及set和get方法
- OC语言——点语法和成员变量的4种作用域及property和synthesize的使用
- 黑马程序员-我的第七篇学习日记:OC成员变量名的命名规范,set方法和get方法
- 【OC语言】set方法和get方法
- 黑马程序员——OC语言------NSString、多文件开发、点语法、成员变量的作用域、@property和@synthesize
- OC--语法变量声明synthesize和property
- 【Objective-C】04-OC对象成员变量的封装规范:get方法和set方法
- 黑马程序员——OC语言------set和get方法(封装)、类方法、self关键字
- OC之点语法、成员变量作用域、@property和@synthesize
- OC基础---NSString、多文件开发、点语法、成员变量的作用域、@property和@synthesize
- OC中的点语法,成员变量,@property和@synthesize:id类型,构造函数
- 黑马程序员_iOS开发之OC之面向对象之多文件操作、点语法、成员变量的作用域和关键字@property与@synthesize
- 黑马程序员-OC学习笔记-点方法、成员变量作用域以及set方法和get方法@property的综合题
- HDU1811 Rank of Tetris(并查集+拓扑排序)
- java volatile关键字
- hdu 1556 Color the ball (树状数组解决区间覆盖+单点查询)
- 25个必须记住的SSH命令
- eclipse myeclipse console日志信息显示不全的解决办法
- OC语言学习 (三) 成员变量get/set方法和“.”语法,@proterty和@synthesize关键字
- Linux脚本-chmod
- 如何修改默认时间格式?24小时制
- 后端工程师与项目经理的区别
- MVC,MVP 和 MVVM 的图示
- 如何在fragment中跳转到acticity
- Java反射技术
- 如何部署Jira并破解汉化成中文
- jdk1.7线程并发的新特性