【问题标题】:Declare properties in .h interface or in an extension in .m file?在 .h 接口或 .m 文件的扩展名中声明属性?
【发布时间】:2013-01-03 02:04:47
【问题描述】:

在 Objective-C 中,最佳实践是:

  1. 在.h中声明按钮等对象,然后在.m中合成

    .h
    @interface SomeViewController : UIViewController  
      @property (strong, nonatomic) UIButton *someButton;  
    @end
    
    .m
    @implementation SomeViewController  
      @synthesize someButton = _someButton;  
    @end
    
  2. 或在 .m 中将它们声明为 ivars

    @interface SomeViewController ()  
      @property (strong, nonatomic) UIButton *someButton;  
    @end  
    

我注意到在很多 Apple 代码中,特别是他们的 Breadcrumbs 示例代码,他们的许多属性都在接口中声明。两者有区别吗?我还注意到,当在@interface 中声明属性时,它们会自动合成带有下划线前缀,从而使someButton = _someButton 合成无用。

【问题讨论】:

  • 这两个声明都是属性声明。 ivar 由@synthesize 创建。它们的功能相同;不同之处在于它们对其他文件的可见性。

标签: objective-c coding-style declared-property


【解决方案1】:

首先,as of Xcode 4.4 不再需要 @synthesize(除非您同时更改 setter 和 getter 方法),无论是在 @interface@implementation 中声明 @property 时。

如果 @property 只能从类中访问,则在 .m 文件的 class extension 中声明 @property。这提供了封装,并且可以很容易地看到 @property 没有被其他类使用。

如果 @property 被其他类使用,按照设计,然后在 .h 文件的 @interface 中定义它。

【讨论】:

  • 我想评论“很少需要使用@synthesize”了。 (在某些情况下,例如只读属性或 Core Data 子类上的属性,实际上仍然需要使用@synthesize,因为 Xcode 仍然不能很好地理解这些。)
  • 我完全同意@JRG-Developer。
  • @Basil 我每周都会检查“使用你的面包”,很棒的东西!感谢您的链接。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-18
  • 1970-01-01
  • 1970-01-01
  • 2020-04-29
  • 2018-04-26
  • 2018-06-16
相关资源
最近更新 更多