cari

Rumah  >  Soal Jawab  >  teks badan

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 hari yang lalu555

membalas semua(1)saya akan balas

  • 大家讲道理

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

    1. Subkelas menulis semula 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: 方法

    balas
    0
  • Batalbalas