搜尋

首頁  >  問答  >  主體

objective-c - iOS中getter/setter的問題

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];
巴扎黑巴扎黑2757 天前559

全部回覆(1)我來回復

  • 大家讲道理

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

    1、子類別重寫了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: 方法

    回覆
    0
  • 取消回覆