属性和成员变量
1)声明属性、成员变量,统一使用属性,而非成员变量:
// 推荐写法
// In the header file
@interface HoriPerson : NSObject
/** 姓 */
@property (copy, nonatomic) NSString *firstName;
/** 名 */
@property (copy, nonatomic) NSString *lastName;
@end
////////////////////////////////////////////
////////////////////////////////////////////
// 不推荐
// In the header file
@interface HoriPerson : NSObject {
NSString *_firstName;
NSString *_lastName;
}
@end
// 推荐写法
// In the implementation file
@interface HoriPerson()
/** 全名 */
@property (copy, nonatomic) NSString *fullName;
@end
@implementation HoriPerson
@end
////////////////////////////////////////////
////////////////////////////////////////////
// 不推荐
// In the implementation file
@implementation HoriPerson {
NSString *_fullName;
}
@end
2)在对象内部统一使用”点语法“来访问实例变量(除init系列方法以及属性的set方法外),而非直接访问实例变量:
// In the implementation file
@interface HoriPerson()
/** 全名 */
@property (copy, nonatomic) NSString *fullName;
@end
@implementation HoriPerson
- (instancetype)initWithFirstName:(NSString *)firstName lastName:(NSString *)lastName {
self = [super init];
if (self) {
// init方法直接访问实例变量
_fullName = [firstName stringByAppendingString:lastName];
}
return self;
}
- (NSUInteger)nameLength {
// 使用"点语法"访问实例变量
return self.fullName.length;
// 不推荐使用
// return _fullName.length;
}
// fullName属性的set方法
- (void)setFullName:(NSString *)fullName {
// 这里必须直接访问实例变量fullName,
// 如果用"点语法"访问fullName,会导致在这个方法中死循环
_fullName = fullName;
}
@end
3)属性的存储策略:nonatomic/atomic,assgin/copy/strong/weak
- NSString、NSArray、NSDitionary类型的对象建议使用copy修饰,防止意外修改属性的值:
@property (copy, nonatomic) NSString *string;
建议使用nonatomic,而非
atomic,atomic修饰的属性线程安全,但会消耗更多的性能;完整的写出存储策略,不可省略:
// 推荐
@property (copy, nonatomic) NSString *string;
// 不推荐
@property (copy) NSString *string;
- 代理(delegate)类型属性使用weak存储策略,以免造成循环引用:
@property (weak, nonatomic) id <HoriMultiLockVeiwDelegate> delegate;
4)属性通常使用懒加载进行初始化:
@property (strong, nonatomic) UITableView *tableView;
- (UITableView *)tableView {
if (!_tableView) {
_tableView = [[UITableView alloc] init];
}
return _tableView;
}