Objective -C 2.0 中,
在接口文件中,即后缀名是.h的文件中,使用@property来标识属性(一般是实例变量);
在实现文件中,即后缀名是.m的文件中,使用@synthesize来标识所声明的 属性,让系统自动生成setter和getter方法
下面是一个例子程序:
#import <Cocoa/Cocoa.h> @interface useProperty : NSObject { int intX; int intY; } @property int intX,intY; @end @implementation useProperty @synthesize intX,intY; -(void) print { NSLog(@"两个数相加的和为:%i",intX+intY); } @end int main(int argc,const char *argv[]){ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; useProperty *testProperty = [[useProperty alloc] init]; [testProperty setIntX:2]; [testProperty setIntY:3]; [testProperty print]; [pool drain] ; return 0 ; }说明:从上面的例子中,我们明明没有定义setIntX和setIntY方法,却可以使用他们 ,这就是使用property的好处,是不是比写setter,getter方法方便多了啊 ...嘻嘻
属性列表中的各个常用属性值及其含义:
属性 含义
assign 使用简单赋值语句为实例变量设置值
copy 使用copy方法设置实例变量的值
noneatomic 直接返回值。若没有声明该属性,那么就是atomic属性,挤兑实例变量的存储是互斥锁定的。在没有垃圾回收的环境下,系统retain这个实例变量,并设置
autorelease 然后才返回值
readonly 不能设置实例变量的值,编译器不生成setter'方法
readwrite 可以获取并设置实例变量的值。在实现类文件中,使用@synthesize,编译器自动产生setter和getter方法,如上面的例子中就是这种情况
retini 在赋值的时候执行retain(保持)操作
getter = name setter方法使用name制定的名称,而不是实例变量的名称
setter = name getter方法使用name制定的名称,而不是实例变量的名称
好困啦,洗洗睡了。明天再接着学习Objective-C的基础语法吧。