Why dequeue reusable cell twice in making custom table view cell - objective-c

I am following a tutorial of making custom table view cell with storyboard. I drag a UILabel as subview of the cell and set its tag to 1. I have two questions regarding the data source code.
What's the purpose of the second dequeue statement? I know it's an init method while not using storyboard to make the custom cell.
What's the difference between tableview and self.tableview?
-(UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
}
NSDictionary *dToAccess = (self.tableView==tableView)?[self.arForTable objectAtIndex:indexPath.row] : [self.arForSearch objectAtIndex:indexPath.row];
[(UILabel*)[cell viewWithTag:1] setText:[dToAccess valueForKey:#"name"]];
[(UILabel*)[cell viewWithTag:2] setText:[dToAccess valueForKey:#"value"]];
return cell;
}

For your first question, the second dequeueReusableCellWithIdentifier: looks like a mistake.
Here is how a UITableView works:
You might have 50 rows in your table, but if only 10 rows are visible at a time, you only need to make 10 cells, and then when the user scrolls, you can reuse cells that have gone offscreen instead of always releasing them and init'ing new cells that come onscreen. A UITableView keeps a list of cells that have gone offscreen and when you call dequeueReusableCellWithIdentifier:, it removes it from the list of offscreen cells and returns it to you. From here you can customize the cell for re-use (change its text, color, etc) and return it. Again, this is not an "init" method, this is returning a pre-existing cell.
So, let's look at what happens when this UITableView is first displayed -- in this example there are 10 visible cells, so the tableView will call tableView:cellForRowAtIndexPath: 10 times to get cells to display in these 10 slots. Every time this is called, you will need to initialize and return a new UITableViewCell to display. (At this point dequeueReusableCellWithIdentifier: will return nil, because you don't have any offscreen cells to re-use yet)
When a user scrolls your list, cells will begin to go offscreen, and new cells will need to appear. You don't need to make new cells, because you have already created as many as will need to be onscreen at a time. You should call dequeueReusableCellWithIdentifier: to get a reference to a cell that has gone offscreen, which you can then re-use.
I would alter your code like this:
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle: UITableViewCellStyleDefault
reuseIdentifier: CellIdentifier] autorelease];
}
Now you are checking for reusable cells before creating new ones.
For your second question,
In your example, tableView refers to the tableView that was passed in (see the "tableView" in your method signature). Separately, if your class has defined a property called tableView, then self.tableView will call the getter for this property.

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.
dequeueReusableCellWithIdentifier method is used to returns a cell if it has been marked as ready for reuse.
So Whenever there are many number of rows in a table view and you are going to scroll it, then the cells which are just passed away from your previous screen before scrolling are get reused instead of creating new one.
And to know the ans of your second que. I think you should refer this link :
http://www.iphonedevsdk.com/forum/iphone-sdk-development/17669-when-use-self-objectname-just-objectname.html

To dequeue twice is not necessary, this block of code is broken.

Related

How to track a tableViewCell that had slid out of the screen?

As we know, UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:1]];method is invalid after the cell is out of our sight. (it's been put to the pool of reusable cells by system) So how do we track the information inside this cell?
I created another cell variable to point to it.In method -(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPathI make _trackMarkCell = cell; trackMarkCell is a property of current controller. This way I can always get the information of the cell. But I feel this way is not that smart, is there any better solution?
Thanks.
So, basically , UITableviewCell is just a view, that is used to display the content in UITableView so from the method -(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath you can crate a new cell or if the cell is already in the pool you can reuse it
come to your question, with the information i mentioned above, the cell holds the information that is used to display on tableview so u just no need to worry about the cell, but the data what you are displayed in the cell. u just keep track of the data and while updating the cell, clear all the information of the cell (which is crated newly or reused from the pool) before using it. for example
lets say suppose u are displaying the image in the cell, but after some time, image in the cell which is changed, in this case u just change the image which is present the datasource not in the cell, if u are using the images array to display the images in the cell,
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kMenuTableCellReuseId];
if(cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kMenuTableCellReuseId];
}
//hear clear all the info present in the cell
//no need of this also u can directly update the cell, but for clarity i mentioned this
cell.myImageView.image = nil;
//just load the cell with new data
cell.myImageView.image = [dataSource objectAtIndex:indexPath.row];
//.... other code
return cell;
}
one more thing using the another cell to keep track of the cell which is present in the pool which might give u different information of other cell. or that cell might be deallocate. so just keep track of the data not the table view cell.
Not sure how you're populating your cells, but if you're feeding the cells via an array of model objects, you'd have access to all your data within that array. You could reference the object with the information you're seeking based on the index within the array (eg. - array[3], where '3' is the index of the object desired)
So how do we track the information inside this cell?
You just don't. Cells don't store information. Cells display information from a data source. You store the data in arrays or Core Data or on a server or anywhere else. Then you just display it in the cells.
What you can do is, you can get data from the cell and put in your collection in UITableViewCell's prepareForReuse method: this will be called before the cell is reused.

Reusing custom UITableViewCells, see old UIView pictures briefly before new pictures load

I have a custom UITableViewCell that contains a UIView, in which I display a couple of pictures.
In my tableView:cellForRowAtIndexPath: function, I call dequeueReusableCellWithIdentifier: to reuse old custom cells, and then I update them with new pictures.
The problem is that when I scroll quickly on my screen, I see flickers of the old pictures before the new ones are loaded, which is unattractive.
I've tried to fix this by:
implementing prepareForReuse in the custom TableViewCell implementation file; this led to the same three UIViews appearing over and over again, and in this case the new pictures stopped loading altogether
clearing the UIView right after calling dequeueReusableCellWithIdentifier by using a for loop to remove all subviews; the app now takes a really long time to load pictures.
What is the best way to fix this, and why do the above errors in my attempted fixes occur? Here is my current code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *cellIdentifier = #"Blah";
blahCell *someCell = (blahCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (!someCell) {
//initialize cell
} else {
someCell.imageContainerView = nil;
}
... (other code here)
}
I'd try setting the cell's imageView property to nil as the first step in your table view data source method cellForRowAtIndexPath.
You can use this UIImageView Category by AFNetworking.
Whenever you have to set a new image you just need to call
[someCell.imageContainerView setImageWithURL:url placeholderImage:placeholderImage];
Now, whenever you scroll, if the image is not loaded you will see a placeholder image instead of seeing previous cell images.

How can I store the UIActivityIndicator state in UITableView?

I have a UITableView which shows file names. When the user taps on the cell, I download the tapped file. For this, I am showing an activity indicator at the left side of a selected cell. After the download ends, the activity indicator will hide. (Remember, the other content in cell wont change).
There is no rule here to click only one cell at a time. The user may tap any number of cells to initiate the download process. I just start the download process and will add it in the operation queue.
Problem: My problem is, consider the scenario where the user taps 3 cells. So three cells will show activity indicator to represent their download processes. If the user scrolls the table view and comes back to the same cells, the activity indicators was hidden. This is because, the tableview's cell creation method will called only for visible cells. So, how can I store the state of each cell's activity indicator?
You can store which file is downloading. And for each row create activity indicator. Something like this:
NSArray* filesArr;
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString* identifier = #"identifier";
YoursTableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if(!cell){
cell = [[YoursTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
}
//.....
if(filesArr[indexPath.row].downloading)
[cell.activity startAnimating];
else
[cell.activity stopAnimating];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if(filesArr[indexPath.row].downloading)
return;
[self startDownload:filesArr[indexPath.row]];
filesArr[indexPath.row].downloading = YES;
[tableView reloadData];
}
As you allude in your question, the issue is in part an artifact of cell reuse. When a cell is dequeued, you must update its activity state on the cell, either by creating a property on the file object for downloading status as Sk0prion suggested, or by some parallel structure.
I would just mention an alternative. If you have only a few cells, you could conceivably bypass cell reuse and store the cells in a dictionary. By avoiding cell reuse, the status in essence, is borne by the cell rather than the object it references. Memory pressure is obviously at issue. I've rarely found a case where this is the preferred solution.

access text in cell.textLabel.text

This seems like a simple thing but I'm stuck.
In my storyboard, I have a cell with text in it's label (using Static Cells). In didSelectRowAtIndexPath, I'm trying to access the cell's textLabel's text. Here's my code, with NSLogging:
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
if (cell.textLabel.text) {
NSLog(#"cell.textLabel.text = %#",cell.textLabel.text);
} else {
NSLog(#"!cell.textLabel.text");
}
NSLog(#"just for fun: cell.textLabel.text = %#", cell.textLabel.text);
The if statement always returns "!cell.textLabel.text" and the last NSLog is always (null) although the storyboard's cell has text in it.
Is cell.textLabel not correct? Should I be looking at another subview of UITableViewCell?
The default cell style of table cells in the Storyboard are of type 'Custom'. Which gives you a blank cell where you can add other types of controls to it.
If you dragged a label onto the cell and changed its text, then you are likely using a Custom style of UITableViewCell.
The property textLabel is only available on cells of types other than Custom, such as Basic, or Detailed.
Therefore you should first check out if these styles meet your requirements and use them instead.
If you really do require a Custom type of cell, you will need to make a subclass of UITableViewCell and create outlets to access your label.

UITableViewCell text filed disappear data on scrolling the tableview

I have a UITableView with custom cells, those cells contain some textFields. Here when I enter some data in textFields and I scroll the table view data it disappears, I think because every time it's creating new cell.
I resolved this issue by using an array and inserting every cell in that, but here I am not able to reuse cells, so we are wasting memory.
Can you tell me prefect way how I should handle this behavior?
Use an array to store the value of the every text field and set the value of the desired text field in the
- (UITableViewCell *)tableView:(UITableView *)tTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
method
It sounds as though it has something to do with how you are creating cells in the tableView:cellForRowAtIndexPath: method. But without seeing your implementation I can only make general suggestions (add your implementation to your question so people can be a bit more specific with their answers).
If you are worried about memory then use the UITableView's inbuilt cell reuse feature by creating your cells in the following way:
NSString *identifier = #"reuseIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier] autorelease];
}
cell.textLabel.text = #"text relating to index path";
The above will check the tableView to see if there are any available cells for reuse. If there are none then nil will be returned. This is where you create a cell using the initWithStyle:reuseIdentifier: method which marks the cell as being suitable for reuse if it is scrolled out of view. This means that you will only ever instantiate, at maximum, the total number of cells that are visible at once, which keeps your table's memory footprint nice and low.
Note that we set the cell's textField.text outside of the nil check - this is to ensure that if we have retrieved a reusable cell we will overwrite its old text content with the text content relevant to the indexPath being passed into the method.