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
以上在子类SmithPerson中没有重写lastName的getter/setter方法,我可以在init中通过self.lastName重新赋值,但是如果我在子类重写了getter/setter,那怎么重新赋值呢?self.lastName会调用子类的setter方法,setter中如果这样赋值就死循环了
- (void)setLastName:(NSString *)lastName { self.lastName = lastName; }
另外:如果将Person和SmithPerson的init方法改成下面这样,同时子类重写父类lastName的getter/setter:
Person - (instancetype)init { self = [super init]; if (self) { **self.lastName = @"abc";** } return self; } SmithPerson - (instancetype)init { self = [super init]; if (self) { } return self; }
那么执行下面语句时,父类初始化时的self.lastName为什么会调用子类的setter
SmithPerson *p1 = [[SmithPerson alloc] init];
1、子类重写了getter/setter
2、