读EffectiveObjective-C2.0(第六条、第七条

2020-10-28  本文已影响0人  LazyLoad

第六条:理解”属性“这一概念

EOCPerson *aPerson = [EOCPerson new];
aPerson.firstName = @"Bob"; // same as
[aPerson setFirstName:@"bob"];

NSString *lastName = aPerson.lastName;  // same as 
NSString *lastName = [aPerson lastName];
@implementation EOCPerson
@synthesize firstName = myFirstName;
@synthesize lastName = myLastName;
@end
@implementation EOCPerson
@dynamic firstName, lastName;
@end

属性特质:属性可以拥有的特质分为四类

@interface EOCPerson : NSObject
@property (copy) NSString *firstName;
@property (copy) NSString *lastName;
- (instancetype)initWithFirstName:(NSString *)firstName lastName:(NSString *)lastName;
@end
  
// EOCPerosn.m
- (instancetype)initWithFirstName:(NSString *)firstName lastName:(NSString *)lastName {
    if (self = [super init]) {
        _firstName = [firstName copy];
        _lastName = [lastName copy];
    }
    return self;
}

第七条:在对象内部尽量直接访问实例变量

对象之外访问实例变量的时候,总是应该通过属性来访问。除了几种特殊情况外,在对象的内部读取实例变量的时候采用直接访问的形式,而在设置实例变量的时候通过属性来访问

看下面这个例子:

// EOCPerson.h
@interface EOCPerson : NSObject
@property (nonatomic, copy) NSString *firstName;
@property (nonatomic, copy) NSString *lastName;

- (NSString *)fullName;
- (void)setFullName:(NSString *)fullName;
@end

// EOCPerson.m 使用点语法访问实例变量实现
- (NSString *)fullName {
  return [NSString stringWithFormat:@"%@ %@", self.firstName, self.lastName];
}

- (void)setFullName:(NSString *)fullName {
  NSArray *components = [fullName componentsSeparatedByString:@" "];
  self.firstName = [components objectAtIndex:0];
  self.lastName = [components objectAtIndex:1];
}

// EOCPerson.m 使用直接访问实例变量方式实现
- (NSString *)fullName {
    return [NSString stringWithFormat:@"%@ %@", _firstName, _lastName];
}

- (void)setFullName:(NSString *)fullName {
    NSArray *components = [fullName componentsSeparatedByString:@" "];
    _firstName = [components objectAtIndex:0];
    _lastName = [components objectAtIndex:1];
}

这两种写法有几个区别:

针对以上的问题,出现了一种折中的方案:在写入实例变量时,通过setter方法来做,而在读取实例变量时,则直接访问实例变量。此方法,既能提高读取的速度,还能控制对属性的写入,还能确保属性内存管理语义贯彻。

上一篇 下一篇

猜你喜欢

热点阅读