Possible Duplicate:
How does an underscore in front of a variable in a cocoa objective-c class work?
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;
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 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.
Moreover, self.users allows differentiating dummy variable in the method name like below,
- (void)assignUsers:(NSMutableArray*)users {
self.users = 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.
When you write
self.users = array;the compiler translates this to[self setUsers:array];When you write
array = self.users;the compiler translates this toarray = [self users];@synthesizeadds an ivar to your object (unless you added it yourself), and implements the-usersand-setUsers:accessor methods for you (unless you provide your own)If you’re using ARC,
-setUsers:will look something like:If you’re using MRC (i.e. ARC is not enabled),
-setUsers:will look something like*:* – Note that this is a simplified, nonatomic implementation of
-setUsers: