【问题标题】:What is the difference between this 2 @synthesize Pattern and which is Recommended?这 2 个 @synthesize 模式和推荐的有什么区别?
【发布时间】:2012-06-13 14:23:55
【问题描述】:

在示例代码中的很多地方,我看到了@synthesize 变量的 2 种不同方式。例如,这里我采用 1 个示例按钮。 @property (strong, nonatomic) IBOutlet UIButton *logonButton;

1.@synthesize logonButton = _logonButton;

2.@synthesize 登录按钮;

在这两种方法中,推荐哪一种?

【问题讨论】:

    标签: objective-c ios properties


    【解决方案1】:

    简答

    首选第一种方法。

    长答案

    第一个示例声明为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]; 
    }
    

    【讨论】:

    • 然而,在 ARC 条件下,我看不出任何区别。也许 alloc/init 方法会有所不同
    • @KaanDedeoglu 我仍然发现在使用 ARC 时使用下划线 ivar 装饰很重要。例如,假设您创建了一个自定义 getter/setter,并在其中添加了一些特殊逻辑。如果您不小心直接设置了 ivar,您将绕过该逻辑,并可能使您的应用程序数据处于不希望的状态。 This post 推断未能将下划线装饰与 ARC 一起使用时的潜在问题。
    • @FreeAsInBeer :感谢您提供的深度信息。这真的很有帮助。
    【解决方案2】:
    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
      }

    【讨论】:

      猜你喜欢
      • 2010-10-22
      • 2011-01-05
      • 2021-12-01
      • 2010-11-12
      • 2019-01-21
      • 2016-04-20
      • 2020-03-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多