天天看点

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;
}