zoukankan      html  css  js  c++  java
  • 关于@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

  • 相关阅读:
    Java技术 第六次实验 计科1501 胡开辉
    Java技术 第五次实验 计科1501 胡开辉
    Java第四次作业
    Java第三次作业
    Css新增内容
    Html5新增特性
    Jquery图集
    选项卡
    轮播图
    标准命名
  • 原文地址:https://www.cnblogs.com/submarinex/p/2584413.html
Copyright © 2011-2022 走看看