Objective-c @property和@Synthesize

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

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

        例:

Test.h

  1. #import <Foundation/Foundation.h>  
  2. @interface Test:NSObject {  
  3.     int intX;  
  4.     int intY;  
  5. }  
  6. @property int intX,intY;  
  7. -(void) print;  
  8. @end  


Test.m

  1. #import "Test.h"  
  2. @implementation Test  
  3. @synthesize intX,intY;  
  4. -(void) print {  
  5.    NSLog(@"intX+intY=%d",intX+intY);  
  6. }  
  7. @end  


ClassTest.m

  1. #import <Foundation/Foundation.h>  
  2. #import "Test.h"  
  3. int main( int argc, const char* argv[]) {  
  4. NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];  
  5.   
  6. Test *test = [[Test alloc]init];  
  7. [test setIntX:1];  
  8. [test setIntY:1];  
  9. [test print];  
  10. [test release];  
  11.   
  12. [pool drain];  
  13. return 0;  
  14. }  

程序运行结果:

  • test.intY = 1;  

    它等价于:

    1. [test setIntX:1];  
    2. [test setIntY:1];  
    同时,需要特别注意:版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:https://www.cnblogs.com/Free-Thinker/p/4962963.html