iOS Development UI Chapter-uitableviewcell performance optimization and caching mechanism

Source: Internet
Author: User

iOS Development UI Chapter-uitableviewcell performance issues

First, some introduction of UITableViewCell

Each line of the UITableView is a UITableViewCell, initialized by DataSource's Tableview:cellforrowatindexpath: method to initialize each row

There is a default child view inside the UITableViewCell: Contentview,contentview is the parent view of the content displayed by the UITableViewCell, which displays some auxiliary indication views

Auxiliary indication View ? is an icon that displays an action, which can be displayed by setting the UITableViewCell accessorytype , which is the default Uitableviewcellaccessorynone ( does not show the auxiliary reference ), the other values are as follows :

Uitableviewcellaccessorydisclosureindicator

Uitableviewcellaccessorydetaildisclosurebutton

Uitableviewcellaccessorycheckmark

You can also customize the secondary indicator view by using the cell's Accessoryview property (?) by placing a switch to the right.

Second, the question

  Cell work: When the program executes, you can see how many bars it creates, and if the view scrolls, then create the new display. (System calls automatically). That is, when a cell appears within the field of view, it is called to create a cell. This logic seems to be fine, but is there really no problem?

When the call is created, we use NSLog to print the message and print the address of the cell that was created. We found that if the amount of data is very large and the user scrolls back and forth in a short period of time, then a large number of cells will be created, and if it is a rollback, by printing the address, we will find that it does not reuse the cell created before, but instead re-creates it and opens up new storage space.

Is there any good solution?

Third, the principle of cell reuse

(1) iOS devices have limited memory, and if you use UITableView to display thousands of data, you need thousands of UITableViewCell objects, which will deplete the memory of your iOS device. To work around this problem, you need to reuse the UITableViewCell object

(2) Weight principle: When scrolling through the list, someUITableViewCellwill move out of the window,UITableViewwill be outside the windowuitableviewcell put in an object pool and wait for reuse. When uitableview requires return datasourceuitableviewcell,uitableviewcell and return to uitableview

(3) Note: There is a very important question: Sometimes you need to customize the UITableViewCell (with the. Subclass inheritance UITableViewCell), and each line is not necessarily the same kind of uitableviewcell, so a A uitableview may have different types of uitableviewcell, and there will be many different types of UITableViewCell in the object pool, so UITableView may get the wrong type when using UITableViewCell. UITableViewCell

Solution? Solution:UITableViewCellHave aNSString *Reuseidentifieruitableviewcell reuseidentifier ( generally used uitableviewcelluitableview requires return uitableviewcelluitableviewcell object.

Image examples:

Note: A window can be placed under (visible) three cells, the entire program only need to create 4 of this type of cell.

Iv. optimized code for cell

code example:

1#import"NJViewController.h"2#import"NJHero.h"34//#define ID @ "ABC"56@interface Njviewcontroller () <uitableviewdatasource, uitableviewdelegate>7/**8* Save all your hero data9*/Ten @property (nonatomic, strong) Nsarray *HerosOne @property (weak, nonatomic) iboutlet UITableView *TableView;1213@end1415@implementationNjviewcontroller1617#pragma mark-Lazy loading-(Nsarray *) heros19{20if (_heros = =Nil) {21st//1. Get the full pathNSString *fullpath = [[NSBundle mainbundle] Pathforresource:@"Heros"OfType:@"Plist"];23//2. More full path loading dataNsarray *dictarray =[Nsarray Arraywithcontentsoffile:fullpath];25//3. Dictionary Turn modelNsmutablearray *models =[Nsmutablearray ArrayWithCapacity:dictArray.count];27for (Nsdictionary *dictInchDictarray) {Njhero *hero =[Njhero herowithdict:dict];29[Models Addobject:hero];30}31//4. Assigning data_heros =[Models copy];33}34//4. Return Data35Return_heros;36}3738-(void) Viewdidload39{40[Super Viewdidload];41//Set the cell height42//Use the property to set the cell height when the cell height of each row is consistentSelf.tableView.rowHeight =160;44}4546#pragma mark-uitableviewdatasource47//How many groups are returned-(Nsinteger) Numberofsectionsintableview: (UITableView *) TableView49{50Return1;51}52//Returns how many rows each group has-(Nsinteger) TableView: (UITableView *) TableView numberofrowsinsection: (nsinteger) Section54{55ReturnSelf.heros.count;56}57//When a cell appears in the field of view, it is called58//Returns which line of a group shows what-(UITableViewCell *) TableView: (UITableView *) TableView Cellforrowatindexpath: (Nsindexpath *) Indexpath60{61//Define variables to hold values for reuse tags62static NSString *identifier =@"Hero";6364//1. First go to the cache pool to find out if there are any cells that meet the criteriaUITableViewCell *cell =[TableView Dequeuereusablecellwithidentifier:identifier];66//2. If there is no qualifying cell in the cache pool, create a cell of your own67if (cell = =Nil) {68//3. Create a cell and set a unique tagCell =[[UITableViewCell alloc] Initwithstyle:uitableviewcellstylesubtitle reuseidentifier:identifier];NSLog (@"Create a new cell");71}72// 4. Set data to cell 73 Njhero *hero = Self.heros[indexpath.row]; Cell.textLabel.text = Hero.name; Cell.detailTextLabel.text = Hero.intro; Cell.imageView.image = [UIImage imagenamed:hero.icon];78 // NSLog (@ "%@-%d- %p ", Hero.name, Indexpath.row, cell); 79 80//3. Return cell81 return cell;82}83 #pragma mark-Controls whether the status bar displays 85/**86 * Returns yes for hidden status bar, N o instead of */88-(BOOL) prefersStatusBarHidden89 {yes;91}92 @end       

The idea of cache optimization:

(1) First go to the cache pool to find if there is a cell that satisfies the condition, if there is, take it directly.

(2) If not, create a cell yourself

(3) Create a cell, and set a unique tag (the one that belongs to "" to cover a chapter)

(4) Set data to cell

Note the point:

Defining a variable to hold the value of the reuse tag is not recommended here (#define来处理), because the variable is used only within the scope, and if the macro definition is used, the definition and use of the location are too fragmented to read the program. Since its value is constant, it is not necessary to open it every time, so it is defined as a static variable with static.

iOS Development UI Chapter-uitableviewcell performance optimization and caching mechanism

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.