self.text = @"Something"
accesses to you private variable _text
using accessor method [self setText:@"Something"]
. The dot notation is just a syntactic sugar. This method can have its own implementation adding extra functionality to just setting value of private variable _text
.
_text = @"Something"
sets the value to the private variable itself directly.
Also, when setting text
property's value outside the class implementation, the accessor [instance setText:@"Something"]
is called automatically to set the value of private variable
Let me show you simple example what could be difference. The method implementation is simple just for educational purposes, so it may not make sense in real code :-)
Imagine you want to log a message to the console every time the value of text
property changes. You can accomplish this by overriding the accessor method - (void)setText:(NSString *)text
like this for example:
- (void)setText:(NSString *)text
{
// You can do whatever you want with the input "text" value, validate the value for example
// Here we just log the text was changed
// In the log message, we still have the old value of the "text" in the private variable "_text"
// so we can log it together with the new value
NSLog(@"Value of \"text\" property changed from \"%@\" to \"%@\"", _text, text);
// Set the new value of the private variable
_text = text;
// From here on, the private variable already has new value and the log line above
// would give the same values between from and to quotes
NSLog(@"Value of \"text\" property is now \"%@\"", _text);
}
So when you set the _text
directly, none of the log messages above would be performed, because you access the variable directly.
On the other hand, setting using accessor method self.text = @"Something"
would cause following to be printed out to the console:
Value of "text" property changed from "(null)" to "Something"
Value of "text" property is now "Something"