IOS Setters and Getters and Underscored Property Names

iosobjective-c

So I have a NSString property named description, defined as follows:

@property (strong, nonatomic) NSMutableString *description;

I'm able to refer to it as _description when I define the getter, as follows:

- (NSString *)description
{
    return _description;
}

However, when I define a setter, as follows:

-(void)setDescription:(NSMutableString *)description
{
    self.description = description;
}

It breaks _description from the aforementioned getter (undeclared identifier). I know I can probably just use self.description instead, but why does this happen?

Best Solution

@borrrden 's answer is very good. I just want to add some details.

Properties are actually just syntax sugar. So when you declare a property like you did:

@property (strong, nonatomic) NSMutableString *description;

It is automatically synthesized. What it means: if you don't provide your own getter + setter (see borrrden's answer), an instance variable is created (by default it has name "underscore + propertyName"). And getter + setter are synthesized according to the property description that you provide (strong, nonatomic). So when you get/set the property, it is actually equal to calling the getter or the seter. So

self.description;

is equal to [self description]. And

self.description = myMutableString;

is equal to [self setDescription: myMutableString];

Therefore when you define a setter like you did:

-(void)setDescription:(NSMutableString *)description
{
    self.description = description;
}

It causes an infinite loop, since self.description = description; calls [self setDescription:description];.

Related Question