天天看點

OC語言[email protected]、@synthesize

一、@property和@synthesize

在類的聲明中我們會寫一大堆的成員變量和成員變量對應的get、set方法,在類的實作中我們還需要将類的set、get方法進行實作,但是無論是類的聲明還是類的實作,很多代碼都是類似的,所有成員變量的set方法都是類似的,所有get方法又是相似的,是以我們在寫代碼的時候發現很多工作都是沒有技術含量的,代碼很多,但是完成的功能都是一樣的。是以蘋果公司為了減少程式員的這些沒有技術含量的工作,讓程式員将精力放在程式的功能上,蘋果公司提供了property和@synthesize。

@property:翻譯:所有者

@synthesize:翻譯:合成、綜合

二、@property和@synthesize的應用示例:

//一般的類的聲明:
@interface Person : NSObject
{
    int _age;    
    int _weight;                
    int _height;    
}
- (void)setAge:(int)age;
- (int)age;

- (void)setWeight:(int)weight;
- (int)weight;

- (void)setHeight:(int)height;
- (int)height;
@end

//應用@property的聲明:(等同于上面的聲明)
@interface Person : NSObject
@property int age;
@property int weight;
@property int height;
@end
           
//一般的類的實作:
@implementation Person
- (void)setAge:(int)age
{
    _age = age;
}
- (int)age
{
    return age;
}

- (void)setWeight:(int)weight
{
    _weight = weight;
}
- (int)weight
{
    return weight;
}

- (void)setHeight:(int)height
{
    _height = height;
}
- (int)height
{
    return _height;
}
@end

//應用@synthesize的類的實作(等同于上面的實作):
@implementation Person
@synthesize age = _age;
@synthesize weight = _weight;
@synthesize height = _height;
@end
           

三、@property和@synthsize解析

1、 @property和@synthsize的這種作用是編譯器的特性,當編譯器遇到@property和@synthsize時就會自動将代碼進行轉化:

2、 @property的作用:可以自動生成某個成員變量的getter和setter的聲明,由左邊自動轉化為右邊代碼:

       @property int age;    <==>   - (void)setAge:(int)age;

                             - (int)age;             

3、 @synthesize的作用:可以自動實作getter和setter;

       @synthesize age = _age;    <==>   - (void)setAge:(int)age

                                {

                                    _age = age;

                                }

                                - (int)age

                                {

                                    return _age;

                                }

            @synthesize char * name;  <==>  - (void)setName:(char *)name  //編譯器會自動生成一個@private的name變量

                                {

                                    name = name;

                                }

                                - (int)name

                                {

                                    return name;

                                }