簡體   English   中英

這2個@synthesize模式和推薦的有什么區別?

[英]What is the difference between this 2 @synthesize Pattern and which is Recommended?

示例代碼中的許多地方我已經看到了2種不同的@synthesize變量方式。 例如,我在這里采取1個樣本按鈕。 @property(強,非原子)IBOutlet UIButton * logonButton;

1. @ synthesize logonButton = _logonButton;

2. @ synthesize logonButton;

在這2種方法中哪一種推薦?

簡答

第一種方法是優選的。

答案很長

第一個示例聲明為logonButton屬性生成的ivar應該是_logonButton而不是默認生成的ivar,它將與屬性( logonButton )具有相同的名稱。

這樣做的目的是幫助防止內存問題。 您可能會意外地將對象分配給您的ivar而不是您的屬性,然后它將不會被保留,這可能會導致您的應用程序崩潰。

@synthesize logonButton;

-(void)doSomething {
    // Because we use 'self.logonButton', the object is retained.
    self.logonButton = [UIButton buttonWithType:UIButtonTypeCustom];


    // Here, we don't use 'self.logonButton', and we are using a convenience
    // constructor 'buttonWithType:' instead of alloc/init, so it is not retained.
    // Attempting to use this variable in the future will almost invariably lead 
    // to a crash.
    logonButton = [UIButton buttonWithType:UIButtonTypeCustom]; 
}
  1. 意味着屬性的自動生成的set / get方法使用具有不同名稱的ivar - _logonButton。

    -(void)setLogonButton:(UIButton)btn {
    _logonButton = [btn retain]; // or whatever the current implementation is
    }

  2. 意味着屬性的自動生成的set / get方法使用具有相同名稱logonButton的ivar。

    -(void)setLogonButton:(UIButton)btn {
    logonButton = [btn retain]; // or whatever the current implementation is
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM