Class - Person
@interface Person : NSObject
@property (nonatomic, copy) NSString *lastName;
@end
@implementation Person
@synthesize lastName = _lastName;
- (instancetype)init {
self = [super init];
if (self) {
_lastName = @"abc";
}
return self;
}
- (NSString *)lastName {
return _lastName;
}
- (void)setLastName:(NSString *)lastName {
_lastName = lastName;
}
@end
Class - SmithPerson
@interface SmithPerson : Person
@end
@implementation SmithPerson
- (instancetype)init {
self = [super init];
if (self) {
self.lastName = @"aaa";
}
return self;
}
@end
The above does not override the getter/setter method of lastName in the subclass SmithPerson. I can reassign the value through self.lastName in init, but if I rewrite the getter/setter in the subclass, how do I reassign it? self.lastName will call the setter method of the subclass. If the value is assigned in the setter like this, it will be an infinite loop
- (void)setLastName:(NSString *)lastName {
self.lastName = lastName;
}
In addition: If you change the init method of Person and SmithPerson to the following, and the subclass rewrites the getter/setter of the parent class lastName:
Person
- (instancetype)init {
self = [super init];
if (self) {
**self.lastName = @"abc";**
}
return self;
}
SmithPerson
- (instancetype)init {
self = [super init];
if (self) {
}
return self;
}
So when the following statement is executed, why does self.lastName when the parent class is initialized call the setter of the subclass
SmithPerson *p1 = [[SmithPerson alloc] init];
1. Subclass rewrites getter/setter
2,