1. 程式人生 > >黑馬程式設計師 —OC(@property和@synthesize)

黑馬程式設計師 —OC(@property和@synthesize)

1.  @property

  @property用在@interface中,寫法如下:

#import<Foundation/Foundation.h>

@interface  Person :NSObject
{
           int  _age ;    <span style="color:#003300;">//   定義成員變數  年齡</span>
           
           int  _height ;  <span style="color:#003300;">//   定義成員變數  身高
</span>      
           NSString  *_name ;  <span style="color:#003300;">//  定義成員變數   姓名
}</span>
@property  int  age ;  <span style="color:#003300;">//  @property作用:可自動生成這個成員變數的setter和getter的宣告
</span>
@property  int  height ;<span style="color:#003300;">  //  相當於height的set和get方法的宣告
</span>
@property NSString  *name ;
@end
 這裡的@property 想當於給成員變數進行set和get 方法的宣告。

  @property   int  age 等同於  如下

- (void)setAge:(int)age;   <span style="color:#003300;"> //   對成員變數 _age的set方法的宣告</span>
-  (int)age;     <span style="color:#003300;">//     對成員變數 _sge方法的get方法的宣告</span>
 當成員變數的型別一致時。可連續進行宣告:
@propery  nt  age , height;  <span style="color:#003300;">//   一般不建議這麼寫,瞭解就可以了</span>
 

2. @synthesize

  用在@mplementation 中

@implementation  Person 

@synthesize  age = _age ;   <span style="color:#003300;">//   對成員變數  _age 進行方法實現</span>
@end
      
 @synthesize 自動生成成員變數的set和get的實現,並且會訪問當前成員的這個變數
等同於下面的這個實現
 - (void)setAge:(int)age    <span style="color:#003300;">//  set方法對成員變數的實現</span>
{
          _age = age ;
}
-  (int)age         <span style="color:#003300;">//   get 方法對成員變數的實現</span>
{
        return  _age ;
}


 @synthesizer 細節:

                     1>  @synthesize   age = _age;

                           set 和get實現中會訪問成員變數_age。

                            如果成員變數 _age不存在時,就會自動生成一個@private的成員變數 _age。

                      2> @synthesize  age

                             set 和get 實現中會訪問成員變數age。

                             如果成員變數age不存在,就會自動生成一個private的成員變數age。

                     3> 手動的實現

                             當手動實現了set 方法,編譯器就只會自動生成get方法。

                             當手動實現了get 方法, 編譯器就只會自動生成set方法。

                             若同時實現了set 和get 方法,編譯器就不會自動生成不存在的成員變數。