关于@synthesize propertyname = _propertyname;的疑问

Q:

@synthesize propertyname = _propertyname; 
为什么要使用 _propertyname?
什么时候用self.propertyname ,什么时候用_propertyname?

A:

当:@synthesize propertyname = _propertyname;

An initialization method is one of two places in which you should not use accessor methods to access properties (the other place is in a dealloc method)In the rest of your code, you should use accessor methods, such as self.name, to get or set an object’s properties.(详见苹果文档“Your Second iOS App: Storyboards”中的Designing the Model Layer章节)
只有在初始化方法和dealloc方法中直接访问属性。
 
在任何方法体内无法直接使用propertyname:如图:

 
 
如果在合成方法中需要访问实例变量,则使用_propertyname;
如果在非合成方法中需要访问实例变量,则使用self.propertyname。
 
 
在getter中,为什么不使用self.propertyname?因为会陷入无限调用getter的死循环中。 如图:

 
 
在非合成方法中,为什么不使用_propertyname?因为不安全,如果property还没被实例化,将什么都不会发生(可能会引起程序崩溃?)。
 
 
不能使用self._propertyname; 如图:

当:@synthesize propertyname;
如果需要访问实例变量,则使用propertyname;
如果需要访问getter方法,则使用self.propertyname。
若属性为私有的,则外部调用必须通过访问合成方法。
 
 
ONLY setters and getters should access the instance variable directly!!
Use “= _propertyname”to choose the name @synthesize uses for its backing instance variable;

 

http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocProperties.html#//apple_ref/doc/uid/TP30001163-CH17-SW1

http://stackoverflow.com/questions/5170631/what-does-synthesize-window-window-do

转载于:https://www.cnblogs.com/submarinex/archive/2012/08/10/2584413.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值