Objective-c - Issues with getters/setters in iOS
巴扎黑
巴扎黑 2017-05-02 09:30:21
0
1
579
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];
巴扎黑
巴扎黑

reply all(1)
大家讲道理

1. Subclass rewrites getter/setter


@interface SmithPerson : Person

@end

@implementation SmithPerson

- (void)setLastName:(NSString *)lastName {
    [super setLastName:lastName];
}

@end

2,

self.lastName = @"abc";
//该方法等价于 [self setLastName:@"abc"];
//self 的类型为SmithPerson,所以会调用SmithPerson 类的 -setLastName: 方法
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template