问题描述
在Objective-C中,最佳做法是:
In Objective-C, is it best practice to:
-
在.h中声明对象在.m中综合。
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.
推荐答案
首先,起,不再需要 @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
不是从另一个类中使用。
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文件中的扩展中声明属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!