07.黑马程序员-@property和@synthesize

来源:互联网 发布:手机格式化后数据恢复 编辑:程序博客网 时间:2024/06/06 12:22

1.@property


a. 用在@interface


b. 用来自动生成某个成员变量的setter和getter的声明(编译器特性


c. @property int age;等价于

-       (void)setAge:(int)age; //setter-       (int)age; // getter

 

2. @synthesize


a. 用在@implementation中


b. 可以自动生成某个成员变量的setter和getter的实现(编译器特性


c.

@synthesize age = _age; // 会访问_age成员变量

等价于

-       (void)setAge:(int)age{            _age =age;}-       (int)age{            return_age;}


3.@synthesize的细节

a.

@synthesize age = _age;

Setter和 getter实现中会访问成员变量_age

如果成员变量_age不存在,就会自动生成一个@private的成员变量_age

 

b.

@synthesize age ;

Setter和 getter实现中会访问成员变量age

如果成员变量age不存在,就会自动生成一个@private的成员变量age

 

c.    手动实现

若手动实现了setter方法,编译器就只会自动生成getter方法

若手动实现了getter方法,编译器就只会自动生成setter方法

注意:编译器自动生成成员变量是因为在getter或者setter中会用到成员变量,如果手动实现饿setter和getter方法,编译器就不会自动生成不存在的成员变量


编译器自动生成的原则:“你有就用你的,你没有我就帮你实现”


d.    @property新特性

自从Xcode4.x后,@property就独揽了@synthesize的功能,也就是说,@property可以同时生成setter和getter的声明和实现

默认情况下,setter和getter方法中的实现,会去访问下划线_开头的成员变量。

0 0
原创粉丝点击