黑马程序员技术交流社区
标题: 省力神器:@property与@synthesize [打印本页]
作者: 崔石炫 时间: 2014-9-24 15:49
标题: 省力神器:@property与@synthesize
面向对象的封装特性要求我们将数据隐藏,提供接口给外界访问。
针对每一个成员变量都要提供set和get方法,这两个方法的代码比较简单,给我们带来大量重复的无价值的工作量,@property与@synthesize就是为这个问题而生。
@property与@synthesize可以让Xcode自动生成成员变量的set和get方法,避免程序员将大量精力花费在没有价值的重复代码上。
@property、@synthesize的用法:
- #import <Foundation/Foundation.h>
- @interface Person : NSObject
- {
- int _age;
- double _weight;
- double _height;
- }
- - (void)setAge:(int) newAge;
- - (int)age;
- @property double weight; // 自动生成属性_weight的set和get方法的声明
- @property double height;
- @end
- @implementation Person
- - (void)setAge:(int) newAge
- {
- _age = newAge;
- }
- - (int)age
- {
- return _age;
- }
- @synthesize weight = _weight; // 自动生成属性_weight的set和get方法的实现,指定该属性访问成员变量_weight
- @synthesize height = _height;
- @end
复制代码
有了@property和@sycthesize,我们的Person类能以更简练的方式声明和实现:
- @interface Person : NSObject
- {
- int _age;
- double _weight;
- double _height;
- }
- @property int age;
- @property double weight , height;
- @end
- @implementation Person
- @synthesize age = _age;
- @synthesize weight = _weight , height = _height; // 不指定访问的变量时,默认访问与@synthesize后的同名的变量,没有该变量则自动生成。
- @end
复制代码
还有更加简洁的写法,- @interface Person : NSObject
- @property int age;
- @property double weight , height;
- @end
- @implementation Person
- @end
复制代码 类的声明中,2行代码可以声明3个成员变量:_age , _weight , _height,以及它们的get和set方法的声明,当implementation实现实现中没有写@synthesize时,@property可以揽过@synthesize的功能,同时生成set和get方法的声明、实现。自动生成的成员变量为@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
private类型的 自己手动定义的话是 protected
作者: wanyiyuan 时间: 2014-9-24 20:45
出去面试100家
作者: 崔石炫 时间: 2014-9-25 01:48
么子意思?
| 欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) |
黑马程序员IT技术论坛 X3.2 |