iOS:使用self和下划线(_)和变量 [英] iOS: Usage of self and underscore(_) with variable

查看:275
本文介绍了iOS:使用self和下划线(_)和变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

我在使用自变量或带有变量名的下划线后非常困惑,如下所示: / p>

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时的理解,操作系统会确保释放以前分配的内存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变量时使用。如果我使用_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 it's 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. Thanks.

推荐答案

我认为考虑编译器如何(或可能)实现属性会有所帮助。

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:

* - Note that this is a simplified, nonatomic implementation of -setUsers:

这篇关于iOS:使用self和下划线(_)和变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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