编写高质量代码的52个有效方法

52个有效方法(7) - 在对象内部尽量直接访问实例变量

2018-08-28  本文已影响14人  SkyMing一C
在对象内部读取数据时,应该直接通过实例变量来读,而写入数据时,则应通过属性来写。
在对象内部访问实例变量时,是通过属性(self.proper)来访问还是通过_proper来访问区别在于是否执行属性的setter、getter方法。
@interface Wrestler : NSObject
 
@property (copy, nonatomic) NSString *name; // 将name声明为属性
 
- (void)smell;
 
@end
 
@implementation Wrestler
@synthesize name = _name; // 属性name可以使用实例变量_name直接访问
 
- (void)setName:(NSString *)aName {
    NSLog(@"Set name");
    _name = [aName copy];
}
 
- (NSString *)name {
    NSLog(@"Get name");
    return [_name copy];
}
- (void)smell {
    NSLog(@"*** Smelling ***");
    
    // 使用dot syntax访问实例变量
    NSLog(@"%@", self.name);
    
    // 直接调用属性的getter方法
    NSLog(@"%@", [self name]);
在初始化方法及dealloc方法中,总是应该直接通过实例变量来读写数据。
@interface Cena : Wrestler
 
- (instancetype)initWithName:(NSString *)aName;
 
- (void)wrestle;
 
@end
 
@implementation Cena
@synthesize name = _name;
 
- (instancetype)initWithName:(NSString *)aName {
    self = [super init];
    
    if (self) {
        NSLog(@"self.name = aName");
        self.name = aName;
    }
    
    return self;
}
 
- (void)wrestle {
    NSLog(@"I'm %@, U can't see me", self.name);
}
 
- (void)setName:(NSString *)aName {
    if (![aName hasSuffix:@"Cena"]) {
        [NSException raise:NSInvalidArgumentException format:@"last name must be Cena"];
    }
    
    _name = [aName copy];
}
 
@end
 (instancetype)init {
    self = [super init];
    
    if (self) {
        NSLog(@"self.name = empty string");
        self.name = @"";
    }
    
    return self;
        Cena *cena = [[Cena alloc] initWithName:@"John Cena"];
        [cena wrestle];
使用Lazy Initialization配置的数据,应该通过属性来读取数据。

@property (strong, nonatomic) NSNumber *chamCount;
- (NSNumber *)chamCount {
    if (!_chamCount) {
        _chamCount = @13;
    }
    
    return _chamCount;

不要在setter/getter方法中调用setter/getter方法。
- (void)setName:(NSString *)aName {
    NSLog(@"Set name");
//    _name = [aName copy];
    self.name = aName;
}
要点:
  1. 在对象内部读取数据时,应该直接通过实例变量来读,而写入数据时,则应通过属性来写。

  2. 在初始化方法及dealloc方法中,总是应该直接通过实例变量来读写数据。

  3. 使用Lazy Initialization配置的数据,应该通过属性来读取数据。

  4. 不要在setter/getter方法中调用setter/getter方法。

上一篇 下一篇

猜你喜欢

热点阅读