objective-c - iOS中getter/setter的問題
巴扎黑
巴扎黑 2017-05-02 09:30:21
0
1
577
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)
大家讲道理

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: 方法
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板