天天看點

OC @property 和 @synthesize 關鍵字

------Java教育訓練、Android教育訓練、iOS教育訓練、.Net教育訓練、期待與您交流! ------- 

@property @synthesize

//
//  Person.h
//  property
//
//  Created by LiuWei on 15/4/14.
//  Copyright (c) 2015年 LiuWei. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface Person : NSObject
{
    int _age;
    int _height;
}

/*
    @prperty 關鍵字, 使編譯器自動生成成員變量的set方法和get方法的聲明
    - (void)setAge: (int)age;
    - (int)age;
*/
@property int age;

@property int height;

@end
           
//
//  Person.m
//  property
//
//  Created by LiuWei on 15/4/14.
//  Copyright (c) 2015年 LiuWei. All rights reserved.
//

#import "Person.h"

@implementation Person

// @synthesize 自動生成age 屬性的 set和get方法的實作
// 屬性名= 成員變量     告訴編譯器生成哪個成員變量的set和get方法
@synthesize age = _age;
/*
 相當于生成如下代碼
- (void)setAge:(int)age
{
    
    _age = age;
}
 
- (int)age
{
    return _age;
}
*/


@synthesize height = _height;
/*
 相當于生成如下代碼
- (void)setHeight:(int)height
{
    _height = height;
}

- (int)height
{
    return _height;
}
*/
@end
           
//
//  main.m
//  property
//
//  Created by LiuWei on 15/4/14.
//  Copyright (c) 2015年 LiuWei. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "Person.h"

int main(int argc, const char * argv[])
{
    
    Person *p = [Person new];
    p.age = 28;
    p.height = 55;
    
    NSLog(@"%i, %i", p.age, p.height);
   
    return 0;
}
           

屬性的最簡寫形式

//
//  Dog.h
//  property
//
//  Created by LiuWei on 15/4/14.
//  Copyright (c) 2015年 LiuWei. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface Dog : NSObject
// 1, 聲明一個_age成員變量 成員變量作用域為 @private
// 2, 生成_age成員變量set方法和get方法的聲明
// 3, 生成_age成員變量set方法和get方法的實作
@property int age;

@end
           
//
//  Dog.m
//  property
//
//  Created by LiuWei on 15/4/14.
//  Copyright (c) 2015年 LiuWei. All rights reserved.
//

#import "Dog.h"

@implementation Dog


@end
           
//
//  main.m
//  property
//
//  Created by LiuWei on 15/4/14.
//  Copyright (c) 2015年 LiuWei. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "Dog.h"


int main(int argc, const char * argv[])
{
    
    Dog *d = [Dog new];
    d.age = 3;
    
    NSLog(@"dog.age = %i", d.age);
   
    return 0;
}