insertRowsAtIndexPaths calling cellForRowAtIndexPath for every row - iphone

I'm trying to insert a bunch of rows into an empty UITableView in one step using insertRowsAtIndexPaths. (I know that this doesn't sound all that useful, but it's a simplified version of what I really need to do.)
The issue I'm seeing is that after I make the insertRowsAtIndexPaths call, I get cellForRowAtIndexPath calls for every row I inserted, rather than just those that are visible.
That doesn't seem right. And it's pretty much useless to me if it does this.
The only slightly odd other artifact I see is that when I do this, it actually seems to animate the rows into place. This isn't the withRowAnimation, since that's set to none. But it seems there's some sort of higher level animation concept going on here. I had the off-idea that as it animated the rows into place it thought it needed cells for more/all the rows until they got pushed off screen. But I can't turn off this animation without just using reloadData which I'd prefer to avoid.
Generally I have a data set that changes behind the scenes. I can carefully go through and construct the changes to generate data for the insert/delete/reload calls. But I can't limit that to what's on screen since then it doesn't match the data provider.
I figure I must be missing something ... any ideas?
(I am doing this within a beginUpdates/endUpdates pair but that seems to make no difference.)

I talked to some Apple folks today. The issue is definitely related to the animation that UITableView does when you insert new rows. This is the animation that happens to create new rows for cells, separate from the animation that is used when those rows are brought in via insertRowsAtIndexPaths.
Since the table-level animation creates new rows through a sort of "grow down" kind of thing, during the insert animation small amounts of many cells are considered visible and the table will call cellForRowAtIndexPath for them.
There doesn't seem to be any alternative implementation for this that works for all cases. The recommended solution for my case is to "lie": figure out what cells will exist on page after the animation and insert those. After that animation completes, insert the remainder of cells that won't show and the table won't call cellForRowAtIndexPath.
This requires implementing an object between the table view and the "real" data source that can "lie" to the table view about the number of rows in the table for the duration of the animation. Painful, but that's apparently what has been done in similar cases.

I had the same problem, what I did was to declare an attribute called bMassiveLoad initialized to false.
Before I do the 'massive load' I set it to true and the first thing I do in the cellForRowAtIndexPath was to check for that attribute.
At the end of the 'maseive load' I set it to false again and call reloadData...
I know that it is not a beautiful answer, but it helps me.

I was able to solve this by combining a few answers from here:
set the massive load boolean as needed as suggested by pocjoc
- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath {
UITableView *tableView = self.tableView;
switch(type) {
case NSFetchedResultsChangeInsert:
massiveLoad = YES;
[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
...
}
}
and reload the visible rows when it ends
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller {
[self.tableView endUpdates];
if (massiveLoad) {
massiveLoad = NO;
[self.tableView reloadRowsAtIndexPaths:[self.tableView indexPathsForVisibleRows] withRowAnimation:UITableViewRowAnimationFade];
}
}

UITableView calls the relevant delegate and data source methods immediately after a call to insertRowsAtIndexPaths to get the cells and other content for visible cells. This is regardless of whether or not animated is set to YES or NO.
See the discussion here
If you only want the tableView to update the visible cells, then just update your dataSource and call [tableView reloadData].

I don't know whether the behavior you describe is correct, but UITableView has got two methods: beginUpdates and endUpdates (here) that are meant to optimize redrawing (so that animating is done only at the end, otherwise they are done one by one and this could possibly produce the call to cellForRowAtIndexPath).
Now, I am not sure if this could help you, but perhaps you can give this a try...

I feel like there may be a different way to go about this, but what I have found is that if you have existing cells in the visible range (for example, if you have 10 cells visible at all times and you initialize the tableView with 10 blank cells), when you add new rows, the extra rows are not called in cellForRowAtIndexPath.
So, what to do about it. This is how I went about fixing this. When I created the tableView, I added cells to the visible region. They were blank. Then, when I inserted new rows, I only added index paths for the extra rows (i.e. if I have 10 visible rows and want to add 50 rows, including the visible rows, I only added 40 since the first 10 already exist). This of course leaves you with 10 blank cells. At this point, you can use:
NSArray *indexPaths = [myTableView indexPathsForVisibleCells];
[myTableView reloadRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationNone];
This selects your 10 visible blank cells and reloads them with the new information you have passed in (I assume you load data into an array for this part). You will need to add a little logic to your cellForRowAtIndexPath method such as:
if (![myDataArray count]) {
// create a blank cell;
} else {
// add context to your cells as you want;
}
This should do the trick for you and only load the cells you have showing on the screen

For swift you can try this
self.mainTableView.beginUpdates()
self.mainTableView.insertRowsAtIndexPaths(indexPaths, withRowAnimation: UITableViewRowAnimation.Fade)
self.mainTableView.reloadRowsAtIndexPaths(self.mainTableView.indexPathsForVisibleRows!, withRowAnimation: UITableViewRowAnimation.Fade)
self.mainTableView.endUpdates()

The UITableView will request the visible cells by cellForRowAtIndexPath: method, and it can reduce the processing time when there are many cells, ex 1k cells, and reduce spent memory by reusable cell mechanism. If you need to process all cells, then you should implement a custom method to re-process your source data, and then call [tableView reloadData] to update the UI.

Related

Last Section Header View not painted after insertRowForIndexpath and deleteRowForIndexpath

I have a setup with sections in a UITableView which all have a custom section header view. Only one section at a time can have visible rows.
To create an effect that displays other cell rows I basically use the following function:
[self.tableView beginUpdates];
if ( sectionHeaderInsert >= 0 && sectionHeaderInsert <= numberOfSectionsInTableView ) {
[ticketReastepsScreenView.tableView insertRowsAtIndexPaths:indexPathsInsert withRowAnimation:UITableViewRowAnimationFade];
}
[self updateTmpSelectedNumberToCurrent];
if ( sectionHeaderRemove >= 0 && sectionHeaderRemove <= numberOfSectionsInTableView ) {
[ticketReastepsScreenView.tableView deleteRowsAtIndexPaths:indexPathsRemove withRowAnimation:UITableViewRowAnimationFade];
}
[self.tableView endUpdates];
Now what happens is that in the end the new section "opens" and the old one "closes" propperly, but: if I have more sections that fit on the screen the last section that is (partly) visible will not repaint propperly - it is completely covered in white.
All sections are asked gor new heights and I think it even asks for new views (which I hae in an array). The views are then asked to [view setNeedsDisplay];
When I scroll a bit so that the last section header disappears and then scroll it back in, it comes to life again and is visible until I change the currently open section again.
UPD: This funny behavior only appears when I do the insertRow and deleteRow together. I can also simply close one section (deleteRow) and then in a section touch-action open the new one (insertRow) and the behavior is different.
I also tried having an endUpdates and beginUpdates in between the two actions - no positive result.
UPD2: When transitioning to the final position (positions are good) I can see the last section header being painted correctly, but then disappear (no animation, simple plain white over it)
Whatever the REAL problem was - I rewrote heavy parts of the TableView and I think what I've learned is:
If you need a UITableViewCell, use a UITableViewCell. If you need a UIView for the section headers, use a UIView for the section headers.
I've mixed the section headers with the TableViewCells just to re-use some code I had in there. Since categories can only extend one specific class I had to use delegation/provider methods/objects to re-use certain code. It may need more subclassing but is actually much safer.
In addition auto-scrolling to a position now works significantly better and the drawing artifacts are gone.

UITableView datasource method does not call in Device 3G iOS4.0

When I call this Code
[[self tableView]reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:0 inSection:kSectionShoppingList]] withRowAnimation:UITableViewRowAnimationNone];
HeightForRowAtIndexPath Calls
But in CellForRowAtIndexPath for section 3 row 0 does not call.
Looking for your suggestion.
and it is specific to Device 3g iOS4.0.1.
Is anyone earlier have faced same issue.
Is the cell you are reloading visible ?
Not sure about iOS4.0.1, don't have it installed to test, but on iOS5+, the cellForRowAtIndexPath is not called if the cell is not visible, just tried it in one of my apps.
The issue i have mentioned look like a bug in iOs4.0.1. anyway I have solved it by reloading whole table using reloadData method instead of reloading particular rows.
Make sure your are reloading sections and rows that are visible and corresponding the the right indices in your tableview. Also check that your tableView delegate and datasource are correctly set.
reloadData method as the following comment :
- (void)reloadData; // reloads everything from scratch. redisplays visible rows. because we only keep info about visible rows, this is cheap. will adjust offset if table shrinks
you may also have trouble reloading single rows if your table is mutating, then you should beginUpdate / endUpdate methods
- (void)beginUpdates; // allow multiple insert/delete of rows and sections to be animated simultaneously. Nestable
- (void)endUpdates; // only call insert/delete/reload calls or change the editing state inside an update block. otherwise things like row count, etc. may be invalid.

how to add smooth scroll to UITbaleview when we adding new row to table view

i am getting images with messages from .net webserver by giving xml input.
that's working fine.
i am sending request for every 3 sec and if any new messages and images are there i just add those messages and images to the array and reload the table view.
That is also fine,But what i need is when i reload table view when ever there is new messages that will be displayed on table view by smooth scrolling the existing row.
same as twitter.
can any one please help me.
Thank u in advance.
if you know the indexPath of newly added row , you could use the below function of UITableView to scroll upto new row with animation (smooth effect).
- (void)scrollToRowAtIndexPath:(NSIndexPath *)indexPath atScrollPosition:(UITableViewScrollPosition)scrollPosition animated:(BOOL)animated
Instead Of completely reloading the table, you should call insertRowsAtIndexPaths:withRowAnimation:
The second option will let you specify how you want it animated
(this will also be much more efficient than reloading all the data every time)
You can do something like the following:
(this makes the assumptions that recievedImageFrom server will be called after the data has already been loaded into the data source object. Also, myDataSourceArray is the array where the data is being stored for the table and myTableView is the UITableView.
-(void)recievedImageFromServer
{
NSUInteger row = [myDataSourceArray count]-1; // This can also be set to 0 if you want
// to insert at the top of the table
NSIndexPath* newIndex = [NSIndexPath indexPathWithIndex:row];
[myTableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndex]
withRowAnimation:UITableViewRowAnimationTop];
}
It will then request the cell from its data source.

Reloading UITableViewCell on select

Okidoke. Here's my problem: I have a series of complex UITableViewCells set up to display stories from a news feed (yawn). What I want to happen, is for the cell background image and height to change on selection (as a means of marking that the story has been read).
Now, prior to setting up dequeueing, I was able to do this with a simple [self.tableView reloadData]. That seems to be a no-go with dequeued cells; reloading the table view does not redraw the cells to match their changed state.
I've tried reloadRowsAtIndex- and while this works - beautifully - for the first cell a user clicks on, it goes wonky after that point: sometimes the cell reloads correctly, sometimes not.
Obviously, each story is an NSMutableDictionary object. I'm using an NSNumber object to track whether or not a story has been read.
I would post the code, and I will if anyone asks, but I'm looking for a generic solution that could be implemented in any UITableViewController (share the love).
So, simply put: how does one reliably redraw complex cells on selection?
Try giving each cell a unique ID in order for dequeuing to work, your cells should be coming back with their changed states if you use a unique id for each cell, so 20 cells = 20 ids, hope this helps
Assuming you have the index path, you can access the cell and manipulate it directly:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// handle the selection...
UITableViewCell *cell = [tableView cellForRowAtIndexPath: indexPath];
if (nil != cell) {
//
// now update the cell to reflect the new state
//
}
}

Is there a better way to determine the right size for a UITableViewCell?

I have a UITableView cell that is going to have a variable size depending on it's content (potentially several lines of text).
SInce it appears that heightForRowAtIndexPath is called before I layout the cell, I just guess the correct height by calling [NSString sizeWithFont] on my text string. Is there a better way to set the height after I've laid out the text in the cell and have an idea of exactly what size it should be?
It's going to sound dumb, but ...uh... "layout your cell before you exit heightForRowAtIndexPath" ;)
Seriously, though -- the OS only ever calls this if it's going to be needed (as in: it's about to create the cell & display it on screen), so laying it out & getting ready to display is not wasted effort.
Note, you do not have to do your layout separately, logic-wise. Just make a call to your [self prepLayoutForCellAtIndex:index] within your heightForRowAtIndexPath routine.
If the data is static, you can create a height table and cache the info.
if (0 == heightTable[index]) {
heightTable[index] = [self prepLayoutForCellAtIndex:index];
}
return (heightTable[index]);
Heck, even if the data changes, you can either recalculate the table value in the method that changes the data, or clear to 0 so it gets recalculated the next time it's needed.
I use the following, usually:
- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath: (NSIndexPath *) indexPath {
UITableViewCell *cell = [self tableView: tableView cellForRowAtIndexPath: indexPath];
return cell.bounds.size.height;
}
Note that I use this for tables where I pre-cache a bunch of rows ahead of time, not for those with a LOT of cells. However, for things like Settings tables, where there are just a few rows, but most likely very differently sized, it works well. For larger tables, I do something along the lines of what Olie suggested.
If you look at SMS.app as example, Apple saves the row height of the cell in the SMS.app sqlite database.