Reputation: 81
It seems that it's unnecessary to use @property when customizing both getter and setter method. Like this.
@property (nonatomic) Person *spouse;
@property (nonatomic, copy) NSString *lastName;
@property (nonatomic, copy) NSString *lastNameOfSpouse;
If I use customize getter and setter like this
- (void)setlastNameOfSpouse:(NSString *)name {
self.spouse.lastName = name;
}
- (NSString *)lastNameOfSpouse {
return self.spouse.lastName;
}
It seems that @property won't synthesis any getter or setter method.
I'd like to know that in this example whether I still need to use @property and whether the attribute used in @property takes effect.
Upvotes: 1
Views: 74
Reputation: 299265
You should definitely still use a property in this case.
So considering this line:
@property (nonatomic, copy) NSString *lastNameOfSpouse;
This is a declaration of the API. If you did not include it in your interface, then other classes could not easily access this property. It is also promise that somehow, objects of this class will respond to -lastNameOfSpouse
and -setLastNameOfSpouse:
. There are a lot of different ways that promise could be fulfilled. One common way is to use compiler-generated methods. Another way is to implement the methods yourself. Another way is to add method implementations at runtime. Another way is to use the message dispatching system. There are a lot of options. Which option you use isn't relevant to the interface.
Before we had properties, we had to declare both methods by hand in the interface:
@interface Person
- (NSString *)lastNameOfSpouse;
- (void)setlastNameOfSpouse:(NSString *)name;
@end
You then had to write each implementation by hand. This was somewhat tedious (so tedious that an entire tool existed purely to write these for you). ObjC2 simplified this pattern by calling it a "property" and allowing it to be declared in a single line (along with some hints about how the methods were expected to be implemented). On request (@synthesize
), the compiler would create the most common implementation for you. Later compiler innovations auto-created implementations for any properties you failed to implement yourself. That made things even nicer. But it's all just compiler niceties that wrap up an API promise. And that's why you include it in the interface.
Upvotes: 2
Reputation: 1946
You can use your own getter/setter with effect of generated one:
@synthesize lastNameOfSpouse = _lastNameOfSpouse;
- (void)setLastNameOfSpouse:(NSString *)lastNameOfSpouse
{
_lastNameOfSpouse = lastNameOfSpouse;
// Add-on code like self.spouse.lastName = name;
}
- (NSString *)lastNameOfSpouse {
return _lastNameOfSpouse;
}
Upvotes: 0