单独在.h文件的interface()方法中定义变量而不综合它有什么区别?
我在 .h 文件的接口方法中定义一个变量,如下所示...
@interface ......{
int a;
}
然后我在 .m 文件中使用它,它工作正常....
我还修改了 .h 文件中的代码
@interface ......{
int a;
}
@property(nonatomic) int a;
,并在 .m 文件中设置了int value as
@synthesize a;
现在也可以正常工作...
这两种情况有什么不同?
I define a variable in .h file's interface method like this...
@interface ......{
int a;
}
Then i use it in .m file, it works fine....
Also i modified the code as
@interface ......{
int a;
}
@property(nonatomic) int a;
in .h file, and in .m file i set the int value as
@synthesize a;
Now also it works fine...
What is the different between both cases?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在第一种情况下,您使用字段,可以直接访问它。
在第二种情况下,您使用访问器定义 Objective C 属性。
In first case you use field, with direct access to it.
In second case you are defining Objective C property, with accessors.
通过声明“a”属性,您允许将 int 存储在您的类中,并且您可以从您的类中访问它 - 但只能在您的类中。如果您希望它成为其他对象可以访问的属性(公共属性),那么您需要 getter 和 setter 方法。
通过在
.h
中将其声明为@property
并在.m
中使用@synthesize
,您可以自动创建两个方法:这里要记住的一件事是,即使在您的类中使用合成属性通常也是一个非常好的主意,因为它们会负责您的内存管理。例如,当您将
@property
标记为retain
时:By declaring your 'a' property you are allowing for the int to be stored in your class and you can access it from within your class - but only within your class. If you want it to be a property that is accessible by other objects (a public property) then you need getter and setter methods.
By declaring it as a
@property
in your.h
and using@synthesize
in your.m
, you are automatically creating two methods:One thing to keep in mind here is that it is often a very good idea to use sythesised properties even within your class because they will take care of your memory management. For example, when you flag the
@property
asretain
:如果您定义并综合了一个属性,那么您还可以使用 int value = self.a; 访问该值。 self.a = newValue;。这也使得该变量可以被其他对象访问。如果没有该属性,您就无法使用
self.
来获取该变量,并且其他对象也无法自动获取该变量。If you define and synthesize a property, then you can also access the value using
int value = self.a; self.a = newValue;
. This also makes the variable accessable to other objects. Without the property, you cannot use theself.
to get to the variable and there is no automatic way for other objects to get to it.当您定义和综合属性时,您告诉编译器为其生成 ivar 和访问器方法(-(int)a; 和 -(void)setA:(int)a_;)。可以使用点语法显式或隐式调用这些方法:
When you define and synthesize a property you tell compiler to generate both ivar and accessor methods (-(int)a; and -(void)setA:(int)a_;) for it. Those methods can be called explicitely or implicitely using dot syntax: