天天看点

Objective-c @property和@Synthesize

        在Objective-c中,使用@property来标识属性(一般是实例变量)。在实现文件中使用@synthesize标识所声明的变量,让系统自动生成设置方法和获取方法。

        也就是说@property和@synthesize配对使用,让系统自动生成设置方法和获取方法。

        例:

Test.h

#import <Foundation/Foundation.h>
@interface Test:NSObject {
    int intX;
    int intY;
}
@property int intX,intY;
-(void) print;
@end
           

Test.m

#import "Test.h"
@implementation Test
@synthesize intX,intY;
-(void) print {
   NSLog(@"intX+intY=%d",intX+intY);
}
@end
           

ClassTest.m

#import <Foundation/Foundation.h>
#import "Test.h"
int main( int argc, const char* argv[]) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];

Test *test = [[Test alloc]init];
[test setIntX:1];
[test setIntY:1];
[test print];
[test release];

[pool drain];
return 0;
}
           

程序运行结果:

intX+intY=2

很显然,在Test类定义和类实现都没有方法:setIntX和setIntY,但是我们在写程序时却能使用这两个方法对类的实例变量进行设置值,这就是@property和@synthesize的结果。

这是@property和@synthesize最简单的用法。

另外,在Objective-c 2.0中,增加了"."操作(点操作符),使用这个操作符可以很方便的访问属性(或者说可以很方便的访问类中的成员变量,有点像C/C++的味道了 ),因些,上面的设置操作也可以写成下面的形式:

test.intX =1;
test.intY = 1;
           

它等价于:

[test setIntX:1];
[test setIntY:1];
           

同时,需要特别注意: "."操作(点操作符)只能使用在setter和getter方法中,而不能用在类的其它方法上。

(在很多书上大部分都采用了点操作符进行介绍,其原理就在这里)

@property还有很多其它的属性。@property和synthesize是让系统自动生成设置方法和获取方法,那么系统自动生成的方法是什么样的?有哪些规则?后继再介绍。

继续阅读