Reputation: 38220
In one of the Standford IOS tutorials, the instructor uses lazy instantiation for creating an instance of calculator engine class.
He uses the second syntax exposed in my former question:
@synthesize myTextField = _myTextField;
In this syntax the getter myTextField
has different name from _myTextField
so it is possible to test
if (_myTextField != nil) { ... }
How do I do this with classical first syntax, since the getter and instance variable name are the same (myTextField
)?
Upvotes: 3
Views: 2371
Reputation: 11174
if you use @sythensize variableName = _variableName;
then the instance variable will be called _variableName
and that is what you need to use to access it directly. variableName
is the name which will be used to generate setters and getters, so self.variableName or [self setVariableName:...]
if you use @synthesize variableName;
then the instance variable will have the same name as the synthesised setters and getters. You can still access the instance variable with variableName = ...
but its easier to get mixed up which one you should be using
so 2 lazy loading implemetations
@synthesize varName = _varName
- (id)varName
{
if (!_varName)
_varName = [[NSObject alloc] init];
return _varName;
}
or
@synthesize varName;
- (id)varName
{
if (!varName)
varName = [[NSObject alloc] init];
return varName;
}
Personally, I go for @synthesize varName = _varName
its much easier to read and harder to mix up when you're accessing the variable when you meant the setter and vice versa
Upvotes: 4