iOS開發之懶加載
在iOS開發中幾乎經常用到懶加載技術,比如我們存放網絡數據的數組,控制器的view,控件的自定義,復雜的運算邏輯等等情況下都會用到懶加載技術,那么什么是懶加載呢?? 他又有什么樣的優點呢??
懶加載:
- 也被成為延遲加載,可以做到用到時再加載
- 加載過了就不會再次加載,節約了系統資源
- 對于實際開發中可能會遇到的一些順序問題,懶加載也能很好的解決
懶加載的實現思路:
- 1.在類擴展中創建一個屬性
- 2.重寫這個屬性對應的getter,將要實現的邏輯放到這個getter中
- 3.考慮到懶加載只加載一次,那么在實現邏輯之前應該判斷一下這個屬性是否為空,為空才執行邏輯,否則直接返回這個屬性
實例代碼:
/** 用戶*/
@interface LXBUserViewController()
@property (nonatomic,strong) NSMutableArray *users;
@end
- (NSMutableArray *)users
{
if (!_users) {
_users = [NSMutableArray array];
}
return _users;
}
我們以后要使用users數組出裝數據的時候,我們直接:
[self.array addObjectsFromArray:(nonnull NSArray *)];
不用再關心users數組該在什么時候創建,我們只使用他就行了,
這樣的話就是的程序會更加的簡潔,提高了程序的可讀性,也能降低程序的耦合性
主要的應用場景:
@interface XMGTopicViewController ()
@property (nonatomic, strong) NSMutableArray *users;
@end
@implementation XMGTopicViewController
- (NSMutableArray *)topics
{
if (!users) {
users = [NSMutableArray array];
}
return _users;
}
// 加載網絡數據
self.users = [LXBUsers objectArrayWithKeyValuesArray:responseObject[@"user"]];
2.用于初始化子控件
在實際開發中不管是通過xib還是純代碼我們都可能會在:
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// 添加子控件
}
return self;
}
初始化子控件,當要添加的子控件數目較多時我們就可以
單獨抽取一個方法addChildView,在里面添加子控件,這樣的話
- (instancetype)initWithFrame:(CGRect)frame方法
看起來就會比較簡介,但是在addChildView中仍然是一堆代碼,
可讀性依然很差,此時我們就可以通過懶加載的方式去添加子控件,比如:
@interface LXBUserCell ()
@property (nonatomic,weak) UIButton *button1;
@property (nonatomic,weak) UIButton *button2;
@property (nonatomic,weak) UIButton *button3;
@property (nonatomic,weak) UIButton *button4;
@end
@implementation LXBUserCell
- (UIButton *)button
{
if (!_button) {
UIButton *button = [[UIButton alloc] init];
[self addSubview:button];
self.button = button;
}
return _button;
}
- (UIButton *)button2
{
if (!_button2) {
UIButton *button = [[UIButton alloc] init];
[self addSubview:button];
self.button2 = button;
}
return _button2;
}
- (UIButton *)button3
{
if (!_button3) {
UIButton *button = [[UIButton alloc] init];
[self addSubview:button];
self.button3 = button;
}
return _button3;
}
- (UIButton4 *)button4
{
if (!_button4) {
UIButton *button = [[UIButton alloc] init];
[self addSubview:button];
self.button4 = button;
}
return _button4;
}
還有其他的情況也會用到懶加載,我就不寫了
注意:很多人都習慣了objc中的點語法,點語法用于方便的通過屬性的setter,getter去操作成員變量,但是在懶加載的編寫過程中應用點語法時一不小心可能會導致程序進入死循環比如:
- (NSMutableArray *)users // 1部分
{
if (!_users) { // 2部分
_users = [NSMutableArray array]; // 3部分
}
return _users; // 4部分
}
第一部分:self.users是一個getter
第二部分:不能寫成 !self.users 這也是一個getter,getter中有getter會造成死循環
第三部分:可以使用self.users,這是一個setter
第四部分:不能使用self.users,這也是一個getter,getter中有getter會造成死循環