2016-09-09 54 views
1

我不知道tableView內存分配過程使用reuseIdentifierstatic或不在tableViewdelegate方法。如果我們有數組從方法返回numberOfRowsInSection方法則多少cell會在內存中後cellForRowAtIndexPath方法通過調用一次[UITableViewCell alloc]alloc方法進行分配的20計UITableViewCell內存分配

讓猜想。

示例代碼:

(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 
    return 20; // array count 
} 

(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

    static NSString *MyIdentifier = @"MyIdentifier"; 

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier]; 

    if (cell == nil){ cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:MyIdentifier]; 
     // how many cell will be alloc here 
    } 

// configure cell 
} 

任何有用的澄清將理解感謝您的時間爲好。

+0

行的高度是多少? – pkc456

+0

@ pkc456'height'由'default'感謝您的時間.. – vaibhav

+0

我試圖添加這個作爲評論,但它太長了。所以請檢查我的[答案](http://stackoverflow.com/a/39406550/988169)。 – pkc456

回答

3

初始時,當您的表格視圖首次在視圖中可見時(比如說一次顯示5個單元格),將會分配5個單元格。當您向下滾動時,而不是實例化新表格時,表格視圖正在使用dequeueReusableCellWithIdentifier已有的表格重新使用。所以這意味着5個單元只在內存中。

因此,A UITableView通常將allocate正好足夠UITableViewCell對象來顯示在表中可見的內容。

這種設計模式被稱爲Object Pooling

+1

很好的解釋+1 :) –

+0

@JaywantKhedkar很高興能幫到 – pkc456

1

您可以使用[tableView visibleCells] count],它返回可見表格單元格的編號,然後多少單元格將被分配到。向下滾動時,不是創建新的tableviewcell,而是使用dequeueReusableCellWithIdentifier.dequeueReusableCellWithIdentifier來重用已存在的表視圖,以幫助使用更少的內存。
示例:
如果屏幕可以放置5個表格單元格,然後重新使用,即使表格有1000個條目,只需要在內存中分配5個表格單元格即可。

+0

感謝@nssam,我把這行代碼計算在可見單元格中? – vaibhav