search

Home  >  Q&A  >  body text

Objective-c - Issues with getters/setters in iOS

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];
巴扎黑巴扎黑2884 days ago608

reply all(1)I'll reply

  • 大家讲道理

    大家讲道理2017-05-02 09:32:21

    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: 方法

    reply
    0
  • Cancelreply