iOS: Usage of self and underscore(_) with variable

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 to array = [self users];

@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)

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
}

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;
}

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


when you are using the self.users, you access the property via the setter or getter.

when you are using the _users, you access the property directly skip the setter or getter.


here is a good demonstration of it:

- (void)setUsers:(id)users {
    self.users = users; // WRONG : it causes infinite loop (and crash), because inside the setter you are trying to reach the property via setter
}

and

- (void)setUsers:(id)users {
    _users = users; // GOOD : set your property correctly
}

this is the point in the case of the getter as well.


about the basic memory management (in case of MRR or ARC): the iOS will dealloc the object if there is no more strong pointer which keeps it alive, no matter how you release the pointer of the objects.