03-@property和@synthesize

1、@property 和@synthesize 的作用

(1) 通过@property可以自动生成属性的set,get方法的声明部分

  生成的是set,get方法是哪个属性的,@property后面的名称就是属性去掉下划线后的部分

书写格式:@property 成员变量数据类型 成员变量去掉下划线后的部分;

        例如:成员变量为 int _age;

正确书写结果为:@property  int age;

注意:1> 这里的数据类型没有小括号括住,@property (int) age;   这么写就错了!!

        2> @property int age; 展开后得到对应的setter  和 getter声明 如下:

      - (void)setAge: (int)age;

      - (int)age;

    绿色部分应该保持一致,再例如:

    @property int age_;  展开后得到的就是:

      - (void)setAge_: (int)age_;

        - (int)age_;

  例如:

  - (void)setName: (NSString *)name;

  - (NSString *)name;

这两行代码可以用 @property  NSString *name; 来代替。即通过@property可以自动生成属性_name的set,get方法声明。

(2) 通过@synthesize可以自动生成属性的set,get方法的实现部分

  规则:要告诉@synthesize生成的set,get方法的实现部分是与声明当中哪一个@property相对应。要想得到_name属性,就要

再写=_name。

 = _name的作用是告诉编译器,要访问哪个成员变量,因此必须写上

书写格式:@synthesize 成员变量去掉下划线后的部分 = 成员变量;

        例如:成员变量为 int _age; 

正确书写结果为:@synthesize age = _age;

注意:1> 这里不需要写数据类型,@synthesize  int age = _age;   这么写就错了!!

        2> @synthesize age = _age; 展开后得到对应的setter  和 getter 实现 如下: 

      - (void)setAge: (int)age

      {

          _age = age;

      }

      - (int)age

      {

          return _age;

      }

  例如: 

      - (void)setName: (NSString *)name

  {

    _name = name;

  }

  - (NSString *)name

  {

    return _name;

  }

这几行代码可以用 @synthesize name = _name; 来代替,即通过@synthesize可以自动生成属性_name的set,get方法实现。

2、@property 和  @synthesize 的练习

   Girl 类,属性:姓名、身高、体重  打印出属性

 1 #import <Foundation/Foundation.h>
 2 //声明
 3 @interface Girl : NSObject
 4 {
 5     NSString * _name;
 6     double _height;
 7     double _weight;
 8     
 9 }
10 @property NSString *name;
11 @property double height;
12 @property double weight;
13 @end
14 
15 //实现
16 @implementation Girl
17 @synthesize name = _name;
18 @synthesize height = _height;
19 @synthesize weight = _weight;
20 @end
21 
22 int main()
23 {
24     Girl *girl1 = [Girl new];
25     girl1.name = @"玲玲";
26     girl1.height = 170.0;
27     girl1.weight = 50.0;
28     NSLog(@"女孩名字叫%@,身高:%.f,体重:%.f", girl1.name, girl1.height, girl1.weight);
29     return 0;
30 }

 3、注意

(1) @property int age;

展开后得到: - (void)setAge: (int)age;

                  - (int)age;

(2) @property int age_;

展开后得到: - (void)setAge_: (int)age_;

 

                  - (int)age_;

(3)@property 必须写在 @interface @end之间

  @synthesize 必须写在 @implementation @end 之间

人生之路,不忘初心,勿忘始终!
原文地址:https://www.cnblogs.com/xdl745464047/p/4001045.html