在.h接口中或在.m文件中的扩展中声明属性? [英] Declare properties in .h interface or in an extension in .m file?

查看:120
本文介绍了在.h接口中或在.m文件中的扩展中声明属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In Objective-C, is it best practice to:


  1. 在.h中声明对象在.m中综合。

  1. Declare objects such as buttons in the .h and then synthesize in the .m

.h
@interface SomeViewController : UIViewController  
  @property (strong, nonatomic) UIButton *someButton;  
@end

.m
@implementation SomeViewController  
  @synthesize someButton = _someButton;  
@end


  • 或在.m中声明为ivars

  • or declare them as ivars in the .m

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


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

    I notice that in a lot of Apple code, specifically their Breadcrumbs sample code, many of their properties are declared in the interface. Is there a difference between the two? I also noticed that when properties are declared in the @interface, they are automatically synthesized with an underscore prefix, making the someButton = _someButton synthesis useless.

    推荐答案

    首先,自Xcode 4.4 起,不再需要 @synthesize 您可以在 @interface 或<$中声明 @property 时更改setter和getter方法c $ c> @implementation 。

    First, as of Xcode 4.4 there is no longer a need to @synthesize(unless you change both the setter and getter method), either when the @property is declared in the @interface or @implementation.

    如果 @property 然后在 @property 在.m文件中自定义ExistingClasses / CustomizingExistingClasses.html#// apple_ref / doc / uid / TP40011210-CH6-SW6rel =nofollowtitle =Apple documentation>类扩展名。这提供了封装,并且很容易看到 @property 不是从另一个类中使用。

    If the @property is only accessed from within the class then declare the @property in a class extension in the .m file. This provides encapsulation and make it easy to see that the @property is not used from another class.

    @property 被其他类用于设计,然后在.h文件中的 @interface 中定义。

    If the @property is used by other classes, by design, then define it in the @interface in the .h file.

    这篇关于在.h接口中或在.m文件中的扩展中声明属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆