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:
- #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:
- #import "Human.h"
-
- @implementation Human
- //这里用@synthesize表示age,height变量的set,get方法的实现。
- @synthesize age;
- @synthesize height;
-
- @end
main.m:
- #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] 年龄20,身高60.500000
这时系统会自动生成age,height的set,get方法,可以直接使用,那还有一种情况,如果我只想让age有get方法,没有set方法怎么办,也就是说在初始化里给一个默认值,而这个值只能被调用,不能被修改,用@property这种方式可以吗?答案是肯定的,因为@property给我们提供了类似参数的一种可选项,关键词是readonly,readwrite,分别对应着只能读不能修改和读写均可,一般我们不设置readwrite,因为默认就是读写状态。看代码:
Human.h:
- #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:
- #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:
- #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;
-
-
- }