UITableView dequeueReusableCellWithIdentifier Theory - iphone

When apple developed the UITableView for the first iPhone they had a problem in performance when scrolling through it. Then one clever engineer discovered that the cause of this was that allocation of objects comes with a price, so he came up with a way to reuse cells.
"Object allocation has a performance cost, especially if the allocation has to happen repeatedly over a short period—say, when the
user scrolls a table view. If you reuse cells instead of allocating
new ones, you greatly enhance table-view performance."
Source: iOS Reference Library
To reuse a cell you use:
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
Now, what I am wondering is, what actually happens here? Does it look in the TableView if there is a cell with that identifier and just returns that one? Well yea duh, but if it sends a reference instead of allocating and I have a table view with let's say 4 cells with the same identifier all visible. How can it multiply itself into four instances without allocating?
I want to know this because I am building a calendar type component and all the cells have the same structure only the text within changes. So if I could somehow reuse my cells instead of allocating I think I might get a better performance.
My own theory is that it allocates the four cells (simply because it has too). When a cell disappears from the screen it will be put in the TableView reuse queue. When a new cell is needed it looks in the que if a cell with the same identifier is available, it invokes prepareForReuse method on that cell and it removes itself from the queue.

dequeueReusableCellWithIdentifier: only returns a cell if it has been marked as ready for reuse. This is why in almost every cellForRowAtIndexPath: method you will see something like
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (nil == cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
}
// Do something to cell
return cell;
In effect, enough rows will be allocated to fill the visible part of the tableview (plus one or two more). As cells scroll off screen, they are removed from the table and marked as ready for reuse. As the queue of "available cells" grows, your line that asks for a dequeued cell will start obtaining a cell to use, at which point you will not have to allocate anymore.

The code for deqeueueReusableCellsWithIdentifier: will look something like this:
(Taken from one of my own projects where I do something similar with views/pages in a paged scroll view)
- (UIView*) dequeueReusablePage
{
UIView* page = [reusablePages_ anyObject];
if (page != nil) {
[[page retain] autorelease];
[reusablePages_ removeObject: page];
}
return page;
}
So it keeps a simple NSMutableSet with reusable objects.
When cells scroll off the screen and are not longer visible, they are put in this set.
So you start with an empty set and the set will only grow if you actually have more data to show then is visible on the screen.
Used cell scrolls off the top of the screen, is put in the set, then taken for the cell that appears at the bottom of the screen.

The purpose of dequeueReusableCellWithIdentifier is to use less memory. if we use 100 cells in a tableView then need to create 100 cells every time.It reduce the app functionality and may cause crash.
For that dequeueReusableCellWithIdentifier initialise the particular number of cells that we created and the cells will use again for further processing.
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *TableIdentifier = #"YourCellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:TableIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TableIdentifier];
}
ExternalClassTableViewCell *myCell = [[ExternalClassTableViewCell alloc]init];
myCell.MyCellText.text = [tableData objectAtIndex:indexPath.row];
myCell.MyCellImage.backgroundColor = [UIColor blueColor];
return cell;
}

Related

Table View Returning Funny Error

Okay I am creating a Table View using objective c, but the data source is not working correctly...
My error:
2012-06-02 20:14:39.891 Dot Golf Scoring[195:707] *** Assertion failure in -[UITableView _createPreparedCellForGlobalRow:withIndexPath:], /SourceCache/UIKit/UIKit-1914.85/UITableView.m:6061
2012-06-02 20:14:39.895 Dot Golf Scoring[195:707] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UITableView dataSource must return a cell from tableView:cellForRowAtIndexPath:'
My Code:
-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 16;
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
return #"Comments On Your Round";
}
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell"];
cell.textLabel.text = #"Text Label";
return cell;
}
Why is the table view not getting filled with this fake data???
You are never initializing cell. Use this code:
- (UITableViewCell *)tableView:(UITableView *)tableView2 cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView
dequeueReusableCellWithIdentifier:#"UITableViewCell"];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:#"UITableViewCell"]
autorelease];
cell.textLabel.text = nil;
}
if (cell) {
//customization
cell.textLabel.text = #"Text Label";
}
return cell;
}
You say you are a noob.... let me explain
First of try picking up the book:
The Big Nerd Ranch Guide
What you are thinking is that dequeueing is basically initializing right? NO! Dequeuing is basically nilling any cell that is not visible, aka you scroll past it. Therefore, cell == nil will be called in probably four situations (that I can think of):
When we first setup the table view (cells will be nil)
When we reload data
Whenever we may arrive at this class
When the cells becomes invisible from the table view
So, the identifier for dequeuing is like an ID. Then in the statement to see if cell is nil, we initialize cell, you can see the overridden init method: initWithStyle. This is just what type of cell there is, there are different types with different variables you can customize. I showed you the default. Then we use the reuseIdentifier which was the dequeuing identifier we said earlier. THEY MUST MATCH! I nil textLabel just for better structure, in this case each cell has the same text so it won't matter really. It makes it so the cell that dequeues comes back with the right customization you implemented. Then once cell is actually valid, we can customize.
Also, you are using the same text for each cell. If you do want to have different text for each cell, familiar yourself with NSArray. Then you could provide the array count in numberOfRowsForSection and then do something like this:
cell.textLabel.text = [array objectAtIndex: [indexPath row]];
Where indexPath is the NSIndexPath argument provided in the cellForRowAtIndexPath method. The row variable is the row number, so everything fits!
Wow, that was a lot to take in right!
Now go stop being an objective-c noob and start reading some books!
For more info read:
Table View Apple Documentation
I don't think you read the Table View Programming Guide or understood the reuse mechanism of UITableViews ;)
Cells in UITableViews are reused/recycled, to avoid reallocating an instance of the UITableViewCell class each time you need a cell. This is because UITableView needs a lot of reactivity, especially when scrolling the tableview as the scrolling needs to be fast, and allocating a new UITableViewCell instance each time would make the tableview hang for a second while the instance is created.
So the idea behind UITableViewCell reuse mechanism is to allocate the minimum amount of cells, and each time you need a cell, try to reuse/recycle a cell that was previously allocated but is no longer user (because it is offscreen since you scrolled).
But if there is no cell available to reuse, you need to allocate one yourself!.
You forgot to do this part in your code, that's why you end up returning a nil cell, which throws the exception.
So the typical code to do this is :
static NSString* kCellId = #"Cell";
// First, try to reuse a cell that was previously allocated
UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:kCellId];
// here, if a cell is returned, that means that we have an old cell
// that was used before but is no longer onscreen (so we can recycle it
// and just actualize its content)
// but if cell is nil, this means the UITableView didn't have a cell available to reuse
// so we need to create a new one
if (cell == nil)
{
// So if we didn't have a old cell ready to reuse that have been returned, create one
cell = [[[UITableViewCell alloc] initWithReusableIdentifier:kCellId] autorelease];
// And configure every properties of the cell that will be common to every cell
// and won't change even if the cell is recycled, eg:
cell.textLabel.textColor = [UIColor redColor];
cell.textLabel.font = [UIFont boldSystemFontOfSize:12];
// etc
}
// And at this point, we have a cell, either newly created or that have been recycled
// So we configure every property that is row-dependant and change for each row, eg:
cell.textLabel.text = [myTextsArray objectAtIndex:indexPath.row];
NB: I never used storyboard but AFAIK, when you use storyboard, you don't need to have the "if" statement and create the cell when no reusable cell is avaiable, as storyboard will create it for you using the cell design in your storyboard. But this is the only case when you don't need to allocate the cell youself.

How do I make my UITableView cells always == nil when viewWillAppear happens? I want to completely reload all my cell views

How do I make my UITableView cells == nil (make them not cached) when viewWillAppear happens? I want to completely reload all my cell views every time I come to the view. The main reason is because the backgroundView image of the cells may changed because of "themes" I'm adding to the app.
[tblView reloadData] doesn't work on the cached views on the cell.
Your cellForRowAtIndexPath method in your table view controller probably has two lines like:
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
These lines attempt to reuse a previously created/formatted cell. To stop this reuse, take these lines out and instead just always allocate a new cell (i.e. something the equivalent of below).
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
Then when you do [tableView reloadData] in your viewWillAppear method it will always create brand new cells for each row rather than trying to reuse old ones.
Before you call reloadData, just let tableView:numberOfRowsInSection: return 0 first.
Then your table will have no row at all.
I would use -tableView:willDisplayCell:forRowAtIndexPath: to determine and set the background views of your cell right before their drawn on screen. Obviously you'll want to use your datasource to determine which background view should be displayed.

How does dequeueReusableCellWithIdentifier: work?

I would like some precision about the dequeueReusableCellWithIdentifier:kCellIdentifier. If I understand well, the hereunder NSLOG is supposed to print just once. But it doesn't. So what is the point of dequeueReusableCell ? Is it only efficient with custom cell ?
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *kCellIdentifier = #"UITableViewCellStyleSubtitle3";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier];
if (cell == nil)
{
NSLog(#"creation of the cell");
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:kCellIdentifier] autorelease];
}
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.textLabel.text = [[self.table objectAtIndex:indexPath.row] objectForKey:kTitleKey];
[cell setBackgroundColor:[UIColor colorWithWhite:1 alpha:0.6]];
return cell;
}
It only comes into play when initialized cells are moved off screen.
For instance, say you have a table view that displays ten cells on screen, but has a hundred rows in total. When the view is first loaded and the table view populated, ten cells will be initialized (hence the multiple NSLog statements). When you start to scroll down, the cells that disappear off the top of the screen are placed into the reuse queue. When the new cells appearing from the bottom need to be drawn they are dequeued from the reuse queue instead of initialising new instances, thereby keeping memory usage down.
This is also why it's important that you configure the properties of your cell outside of the if (cell == nil) condition.
Start to scroll on your tableview and you should see that the log message doesn't appear anymore.
if you have a tableview that has a height of 1000 pixels, and each cell has a height of 100 pixels you will see the log message 11 times.
Because 11 is the maximum amount of cells that are visible at the same time.
It's 11 and not 10 because when you scroll down a little there will be 9 cells that are fully visible and 2 cells that are only partial visible.

Deleting a cell in tableview, the cell also can be reused,why?

at first,i delete one cell in tableView,then i want to add another new cell in the tableView,but the new cell is not new,it is just the cell which i delete. i know what dequeueReusableCellWithIdentifier means.i think when delete one cell,the cache in dequeueReusableCellWithIdentifier is also deleted.why not?
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(#"table reload");
PDFModel* tempmodel=[PDFArray objectAtIndex:indexPath.row];
NSString * CellIdentifier=tempmodel.PDFName;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
NSLog(#"cell %x",cell);
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
//custom the cell
cell.text=...
}
return cell;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle==UITableViewCellEditingStyleDelete)
{
[PDFArray removeObjectAtIndex:indexPath.row];
NSMutableArray* array=[[NSMutableArray alloc] init];
[array addObject:indexPath];
[self.tableView deleteRowsAtIndexPaths:array withRowAnimation:UITableViewRowAnimationRight];
}
}
There's no reason to delete the UITableViewCell since it can be reused. That cell won't be displayed until it is processed again by cellForRowAtIndexPath, so it won't show up with the old data. The laid-out cell, though -- the view and all of its subviews -- can be reused after new data replaces the old data.
Think of it like each cell is a whiteboard (dry erase board) where it's cut down to a certain size and all of the basic information areas are etched into the surface: a place for some text, another area for a number, a special space for drawing a picture, etc. In tableView:cellForRowAtIndexPath: when you check whether the cell == nil, you're trying to find out if there are any already-etched whiteboards available that you can erase and write the new information on with your dry erase marker. If there aren't then it cuts out and etches a brand new board to write information on, but if there is one that can be erased then it just wipes off the old information with an eraser and writes in the new information. As you can imagine, this saves a lot of time.
When a user is scrolling the table what's actually happening is that when one cell (whiteboard) scrolls off the top and is no longer visible, the system erases the data and moves it to the bottom of the stack; it will be the next one to scroll into view. As a result the system only has to create as many whiteboards as can be visible at any one time -- the ones off-screen don't actually exist.
When you delete a cell all you're really doing is telling the table to (a) stop displaying that cell, and (b) setting a flag so the table can use the eraser to wipe off the old data but still reuse the whiteboard.
Creating cells can be very costly in terms of computing power. If a UITableView had to create a new cell every time one came into view while the user was scrolling -- in the analogy, if it had to cut out a new whiteboard and etch all of the areas into it every time one came into view -- the scrolling would be very jerky and look terrible. By reusing cells, replacing just the changing contents, the table can move smoothly as the user interacts with it.
Your question is a bit weird, but I guess you're wondering what the following code does?
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
What the code does, is that it tries to retrieve a cached UITableView cell. This is to reduce memory usage on the iPhone.
Once you delete a cell, you should also remove the data from the datasource (usually an array), e.g.:
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle==UITableViewCellEditingStyleDelete)
{
// remove object from array ...
[dataArray removeObjectAtIndex:indexPath.row];
}
}
(Remember: you can only remove items from an NSMutableArray at runtime, not from a NSArray)
If the cell gets redrawn, you will first check which cell needs to be redrawn, then you retrieve the appropriate data from the datasource, this is all done by the UITableViewDataSource delegate methods. You only have to make sure to retrieve the right content from the array and update the cell's content on redraw, e.g. like this:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"CellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
// no cached cell is found, create a new cell ...
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
// add some defaults for cells in the initializer,
// stuff that's done here should be important for
// all displayed cells, for example background image.
}
// update the cell's content, e.g.: - it will only display content that's currently in the array, deleted objects shouldn't exist in the array at this point
NSString *title = [dataArray objectAtIndex:indexPath.row];
[cell.textLabel setText:title];
return cell;
}
I think You can use
NSString *CellIdentifier = [NSString stringWithFormat:#"Cell%d",indexPath.row];
instead of
NSString * CellIdentifier=tempmodel.PDFName;
please replace it & check it. I think it's helpful to you.
You seem confused by the difference between deleting a cell (an objective-c UI object) and the data it displays.
When you allow a user to delete a cell in the user interface you need to delete the corresponding data from your data model
The implementation of UITableView is highly optimized in iOS and it caches cells (UI objects) to improve performance. You don't really need to be concerned about this as your table will be optimally loaded and displayed based on your data.
In tableView:cellForRowAtIndexPath: you do the following:
Attempt to dequeue a cell instance. This takes advantage of caching done by UITableView
If dequeue does not return a cell, create a new one.
Once you have a cell, configure it with the appropriate data from your data model
When a user chooses a delete action from a cell, delete the data from your data model. optionally, you can animate removing the cell from the table or simply reload the whole table.
The specifics of #4 depend on the user interface you want and how you've configured your data model.
The Apple docs are pretty good about explaining this.
http://developer.apple.com/library/ios/#documentation/userexperience/conceptual/TableView_iPhone/AboutTableViewsiPhone/AboutTableViewsiPhone.html

UITableView with a single custom Cell? (iPhone)

I have run into a bit of a problem. Usually when dealing with UITableView I will build a special
method, configureCell, that builds the cells as the tableView needs them. So cellForRowAtIndexPath queries the configureCell to get a new cell if none is found in the cache.
In the part of cellForRowAtIndexPath that gets run every time a user scrolls:
- (UITableViewCell *)tableView:(UITableView *)theTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [theTableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
[self configureCell:cell atIndexPath:indexPath];
}
//this part is always executed!
}
I set the label values etc. from my model. This works fine and this, I believe, is how it should be to work properly and be the least strain on the CPU. From what I can read in the TableView Guide.
My problem is now that the first Cell in my tableView is different than the others. I has a special icon and other things that separates it from the other cells.
In my configure cell I then tried asking:
if (indexPath.row == 0) {
//do special setup!
}
This is a bad idea as the tableView lazy loads the cells and therefore the first cell that is off-screen, when being scrolled on-screen, will also get indexPath.row = 0 so now I have a "special cell" for every 7 cells.
How do I get around this one?
A second problem that also originates from the above: I have a custom UIView placed in all the cells accessoryView. When the user taps an "Edit" button, all the cells accessoryViews should change to an icon indicating that we are in "Edit mode". Here, again, this only happens for the cells on screen, when scrolling "old" cells are either fetched from cache or new cells are build that doesn't know we are in edit mode.
When You tap a Cell, there is never any doubt about the indexPath.row of the cell tapped, this index you need to pair with your model array to figure out what the user tapped. But it seems different rules apply when the TableView is manipulating the cells (pulling them on-screen, off-screen, deleting, adding).
I guess, I am asking; to follow best practice and not fight the SDK, what should I do to obtain the desired functionality and at which stage in the Cell life-cycle should I apply this logic?
Hope someone can guide me in the right direction:) thank You in advance:)
I think the problem is not that the first off-screen cell is at indexPath.row = 0.
The problem is that you are using the same CellIdentifier for regular and custom cells. So when the TableView goes to dequeue a cached cell, it is sometimes grabbing your custom cell that has the icon in it.
Since you gave it the same CellIdentifier as your regular cells, it doesn't know that they are not the same.
Something like this should fix it:
static NSString *CellIdentifier;
if([indexPath row] == 0){
CellIdentifier = #"CustomCell";
} else {
CellIdentifier = #"Cell";
}
I'm not sure about your edit button problem, but it could be related.