IOS 懶載入模式

來源:互聯網
上載者:User

標籤:

iOS開發—懶載入

1.懶載入——也稱為消極式載入,即在需要的時候才載入(效率低,佔用記憶體小)。所謂懶載入,寫的是其get方法.

注意:如果是懶載入的話則一定要注意先判斷是否已經有了,如果沒有那麼再去進行alloc init

2.我們知道iOS裝置的記憶體有限,如果在程式在啟動後就一次性載入將來會用到的所有資源,那麼就有可能會耗盡iOS裝置的記憶體。這些資源例如大量資料,圖片,音頻等等

下面舉個例子:

1> 定義控制項屬性,注意:屬性必須是strong的,範例程式碼如下:

    @property (nonatomic, strong) UIImageView *icon;

    @property (nonatomic, strong) UIButton *nextBtn;

    @property (nonatomic, strong) NSArray *imageList;

2> 在屬性的getter方法中實現懶載入,範例程式碼如下:

// 懶載入-在需要的時候,再執行個體化載入到記憶體中

/***圖片控制項的消極式載入 ***/

-(UIImageView *)icon

{

    //判斷是否已經有了,若沒有,則進行執行個體化

    if (!_icon) {

        _icon=[[UIImageView alloc]initWithFrame:CGRectMake(x, y, w, h)];

        UIImage *image=[UIImage imageNamed:@"icon"];

        _icon.image=image;

        [self.view addSubview:_icon];

    }

    return _icon;

}

/***按鈕的消極式載入 ***/

-(UIButton *)nextbtn

{

    //判斷是否已經有了,若沒有,則進行執行個體化

    if (!_nextbtn) {

        _nextbtn=[UIButton buttonWithType:UIButtonTypeCustom];

        _nextbtn.frame=CGRectMake(0, self.view.center.y, 40, 40);

        [_nextbtn setBackgroundImage:[UIImage imageNamed:@"normal"] forState:UIControlStateNormal];

        [_nextbtn setBackgroundImage:[UIImage imageNamed:@"highlighted"] forState:UIControlStateHighlighted];

        [self.view addSubview:_nextbtn];

        [_nextbtn addTarget:self action:@selector(nextClick:) forControlEvents:UIControlEventTouchUpInside];

    }

    return _nextbtn;

}

/*** array的get方法 ***/

- (NSArray *)imageList{

    // 只有第一次調用getter方法時,為空白,此時執行個體化並建立數組

    if (_imageList == nil) {

        // File表示從檔案的完整路徑負載檔案

        NSString *path = [[NSBundle mainBundle] pathForResource:@"ImageData" ofType:@"plist"];

        _imageList = [NSArray arrayWithContentsOfFile:path];

     }

    return _imageList;

}

如上面的代碼,有一個_imageList屬性,如果在程式的代碼中,有多次訪問_imageList屬性,例如下面

    self.imageList ;self.imageList ;self.imageList ;

雖然訪問了3次_imageList 屬性,但是當第一次訪問了imageList屬相,imageList數組就不為空白,
當第二次訪問imageList 時  imageList != nil,就不會再次在PList檔案中載入資料了。

3. 使用懶載入的好處:

(1)不必將建立對象的代碼全部寫在viewDidLoad方法中,代碼的可讀性更強

(2)每個控制項的getter方法中分別負責各自的執行個體化處理,代碼彼此之間的獨立性強,松耦合

  (3) 只有當真正需要資源時,再去載入,節省了記憶體資源。

IOS 懶載入模式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.