黑马程序员技术交流社区

标题: 省力神器:@property与@synthesize [打印本页]

作者: 崔石炫    时间: 2014-9-24 15:49
标题: 省力神器:@property与@synthesize
面向对象的封装特性要求我们将数据隐藏,提供接口给外界访问。
针对每一个成员变量都要提供setget方法,这两个方法的代码比较简单,给我们带来大量重复的无价值的工作量,@property@synthesize就是为这个问题而生。
@property@synthesize可以让Xcode自动生成成员变量的setget方法,避免程序员将大量精力花费在没有价值的重复代码上。
@property@synthesize的用法:
  1. #import <Foundation/Foundation.h>

  2. @interface Person : NSObject
  3. {
  4.         int _age;
  5.         double _weight;
  6.         double _height;
  7. }
  8. - (void)setAge:(int) newAge;
  9. - (int)age;

  10. @property double weight; // 自动生成属性_weight的set和get方法的声明
  11. @property double height;

  12. @end

  13. @implementation Person
  14. - (void)setAge:(int) newAge
  15. {
  16.         _age = newAge;
  17. }
  18. - (int)age
  19. {
  20.         return _age;
  21. }
  22. @synthesize weight = _weight; // 自动生成属性_weight的set和get方法的实现,指定该属性访问成员变量_weight
  23. @synthesize height = _height;

  24. @end
复制代码

有了@property@sycthesize,我们的Person类能以更简练的方式声明和实现:
  1. @interface Person : NSObject
  2. {
  3.         int _age;
  4.         double _weight;
  5.         double _height;
  6. }

  7. @property int age;
  8. @property double weight , height;

  9. @end

  10. @implementation Person

  11. @synthesize age = _age;
  12. @synthesize weight = _weight , height = _height; // 不指定访问的变量时,默认访问与@synthesize后的同名的变量,没有该变量则自动生成。

  13. @end
复制代码

还有更加简洁的写法,
  1. @interface Person : NSObject

  2. @property int age;
  3. @property double weight , height;

  4. @end

  5. @implementation Person
  6. @end
复制代码
类的声明中,2行代码可以声明3个成员变量:_age , _weight , _height,以及它们的getset方法的声明,当implementation实现实现中没有写@synthesize时,@property可以揽过@synthesize的功能,同时生成setget方法的声明、实现。自动生成的成员变量为@property后面的变量加上下划线,及@property age会自动生成一个成员变量_age

作者: songxing10000    时间: 2014-9-24 16:17
基础班已经讲了
作者: shileishihai    时间: 2014-9-24 16:23
认识到一个问题,和技术面试官进行技术沟通,要求很强的沟通能力。我平时偏内向,怎么解决这个问题?
作者: Jr_711    时间: 2014-9-24 16:27
补充个小知识点:

有没有注意到@property自动生成的成员变量的默认作用域是@protected还是@private?

作者: 水了个淼    时间: 2014-9-24 20:11
Jr_711 发表于 2014-9-24 16:27
补充个小知识点:

有没有注意到@property自动生成的成员变量的默认作用域是@protected还是@private?

private类型的  自己手动定义的话是 protected
作者: wanyiyuan    时间: 2014-9-24 20:45
出去面试100家
作者: 崔石炫    时间: 2014-9-25 01:48
wanyiyuan 发表于 2014-9-24 20:45
出去面试100家

么子意思?




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2