在.h接口或.m文件的扩展名中声明属性?

Hig*_*asy 13 coding-style objective-c declared-property

在Objective-C中,最佳做法是:

  1. 在.h中声明诸如按钮之类的对象,然后在.m中进行合成

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

    @interface SomeViewController ()  
      @property (strong, nonatomic) UIButton *someButton;  
    @end  
    
    Run Code Online (Sandbox Code Playgroud)

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

zap*_*aph 32

首先,从Xcode 4.4开始,不再需要@synthesize(除非你更改了setter和getter方法),无论@property是在@interfaceor中声明的@implementation.

如果@property仅从类中访问,则在.m文件@property中的类扩展中声明.这提供了封装,并且可以很容易地看到@property不使用其他类.

如果@property其他类按设计使用,则@interface在.h文件中定义它.