objective-c中的@property,@synthesize等简易用法(8)
objective-c中的@property,@synthesize等简易用法(八)holydancer原创,如需转载,请在显要位置注明:转自holy
objective-c中的@property,@synthesize等简易用法(八)
holydancer原创,如需转载,请在显要位置注明:
转自holydancer的CSDN专栏,原文地址:http://blog.csdn.net/holydancer/article/details/7355833
?
在objective-c中,我们可以用new简单的代替alloc init,我们今天介绍的是类似于new这种简易用法的另一种OC特性,用@property,@synthesize来代替get,set方法,用起来很简单,可以省掉很多的代码量,当需要用SET,GET方法的地方,我们可以用@property,@synthesize来简单的代替,这时系统会自动给我们生成该变量的set,get方法,@property对应方法的声明部分,@synthesize对应方法的实现部分。
Human.h:
?
[plain]?view plaincopy?
- #import?<Foundation/Foundation.h>??
- ??
- @interface?Human?:?NSObject??
- {??
- ????int?age;??
- ????float?height;??
- }??
- //这里用@property表示,代表了age和height的set,get方法的声明??
- @property?int?age;??
- @property?float?height;??
- ??
- @end??
Human.m:
?
?
[plain]?view plaincopy?
- #import?"Human.h"??
- ??
- @implementation?Human??
- //这里用@synthesize表示age,height变量的set,get方法的实现。??
- @synthesize?age;??
- @synthesize?height;??
- ??
- @end??
main.m:
?
?
[plain]?view plaincopy?
- #import?<Foundation/Foundation.h>??
- #import?"Human.h"??
- int?main(int?argc,?const?char?*?argv[])??
- {??
- ????NSAutoreleasePool?*pool=[[NSAutoreleasePool?alloc]init];??
- ??????
- ????Human?*human?=?[[Human?alloc]init];??
- ????//“.”在等号左边,相当于set方法。??
- ??????
- ????human.age=20;?//等价于[human?setAge:20]??
- ????human.height=60.50;??
- ??????
- ????//“.”在等号右边,相当于get方法。??
- ????float?tmp=human.height;//等价于?float?tmp?=?[human?height]??
- ????NSLog(@"年龄%d,身高%f",human.age,tmp);??
- ??????
- ????[human?release];??
- ????[pool?release];//相当于对池中每个对象执行了一次release;??
- ??????
- ??
- }??
?
输出语句:
?
2012-03-15 10:11:34.052 String[325:403]?[plain]?view plaincopy?
- #import?<Foundation/Foundation.h>??
- ??
- @interface?Human?:?NSObject??
- {??
- ????int?age;??
- ????float?height;??
- }??
- //这里用@property表示,代表了age和height的set,get方法的声明??
- @property?(readonly)int?age;??
- @property?float?height;??
- ??
- @end??
Human.m:
?
?
[plain]?view plaincopy?
- #import?"Human.h"??
- ??
- @implementation?Human??
- //重写init方法给age赋初值??
- -(id)init??
- {??
- ????if(self=[super?init])??
- ????{??
- ????????age=20;??
- ????}??
- ????return?self;??
- }??
- //这里用@synthesize表示age,height变量的set,get方法的实现。??
- @synthesize?age;??
- @synthesize?height;??
- ??
- @end??
main.m:
?
?
[plain]?view plaincopy?
- #import?<Foundation/Foundation.h>??
- #import?"Human.h"??
- int?main(int?argc,?const?char?*?argv[])??
- {??
- ????NSAutoreleasePool?*pool=[[NSAutoreleasePool?alloc]init];??
- ??????
- ????Human?*human?=?[[Human?alloc]init];??
- ????human.height=60.5;??
- ????//human.age=30;?该行如果不注释是会报错的,即age只有get方法,没有set方法??
- ????NSLog(@"年龄age=%d",human.age);??
- ??????
- ?????
- ????[human?release];??
- ????[pool?release];//相当于对池中每个对象执行了一次release;??
- ??????
- ??
- }??
输出:
?
2012-03-15 10:32:11.497 String[360:403]??
关键字:objective-c ,objective c , oc ,@property , @synthesize