iOS:将 self 和下划线(_)与变量一起使用 [英] iOS: Usage of self and underscore(_) with variable
问题描述
可能的重复:
cocoa Objective-c 类中变量前面的下划线是如何工作的?
在合成如下后,我对使用 self 或下划线和变量名感到非常困惑:
I have been very confused with using self or underscore with variable name after synthesizing it like below:
In .h file:
@property(nonatomic, strong) NSMutableArray *users;
In .m file:
@synthesize users = _users;
根据我在使用 self.users
时的理解,OS 会确保在 set 方法中释放先前分配的内存,因此我们不需要明确注意.
Based on my understandings when I use self.users
, OS will make sure to release previously allocated memory in set method so we don't need to take care explicitly.
_users
是用户的实例变量,通常在访问用户变量时使用.如果我使用 _users
来改变它的值,那么它不会触发 KVO 委托,它不会通知观察用户值变化的类.
_users
is an instance variable for users and should be normally used while accessing the users variable. If I use _users
to change its value then it won't fire KVO delegate which will not notify a class observing users value change.
此外,self.users
允许在方法名称中区分虚拟变量,如下所示,
Moreover, self.users
allows differentiating dummy variable in the method name like below,
- (void)assignUsers:(NSMutableArray*)users {
self.users = users;
}
有人可以告诉我在使用 _users
或 self.users
时是否有任何我理解错误或遗漏的地方吗?
Could someone please tell me if there is anything that I understood wrong or missing while using _users
or self.users
?
推荐答案
我认为考虑编译器如何(或可能)实现属性会有所帮助.
I think it helps to consider how properties are (or might be) implemented by the compiler.
当您编写 self.users = array;
时,编译器会将其转换为 [self setUsers:array];
当您编写 array = self.users;
时,编译器会将其转换为 array = [self users];
When you write self.users = array;
the compiler translates this to [self setUsers:array];
When you write array = self.users;
the compiler translates this to array = [self users];
@synthesize
向您的对象添加一个 ivar(除非您自己添加),并实现了 -users
和 -setUsers:
为您提供的访问器方法(除非您提供自己的)
@synthesize
adds an ivar to your object (unless you added it yourself), and implements the -users
and -setUsers:
accessor methods for you (unless you provide your own)
如果您使用 ARC,-setUsers:
将类似于:
If you're using ARC, -setUsers:
will look something like:
- (void)setUsers:(NSArray *)users
{
_users = users; // ARC takes care of retaining and release the _users ivar
}
如果您使用的是 MRC(即未启用 ARC),-setUsers:
将类似于*:
If you're using MRC (i.e. ARC is not enabled), -setUsers:
will look something like*:
- (void)setUsers:(NSArray *)users
{
[users retain];
[_users release];
_users = users;
}
* - 请注意,这是 -setUsers 的简化非原子实现:
这篇关于iOS:将 self 和下划线(_)与变量一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!