Memory Handling for thumbnail images in UITableViewCells - iphone

Short Explanation
Currently I have a UITableView which contains cells of videos from a website. In addition each cell (which represents a video) has a specific thumbnail image. These images are downloaded asynchrounously using NSURLConnection (so I do not have to worry about threading myself). When these image objects have downloaded they simply notify the UITableView to refresh the cell it belongs to.
My Problem
As standard there will be fetched 10 new videos to the UITableView each call. This means that the user is allowed to push a cell at the bottom of the UITableView to request 10 new videos and so forth. The problem here is that there will quickly be a whole lot of memory usage because data for all thumbnail images (in the UITableView) will still exists no matter what.
Is there a smart way in which you can de-allocate image objects that aren't currently in the view?
Also, the UITableView simply renders all its cells directly from an array I have of all video objects ever fetched from the website. This means there is no limits as to how many times the user can request new videos, making this array bigger and bigger all the time. Is it correct to keep these kind of arrays in memory all the time? Or should you instead delete the ones which goes out of the view and request them again later on?
Thank you in advance

If you're using the standard method approach of queuing and de-queuing cells in your tableview, then you really should only be using a handful of cell views (and their related thumbnails) - eg, the total number of cell views allocated should never be more than the maximum number viewable on screen, and by extension, the number of allocated/references to thumbnail images should not exceed the total number of cells. Each time you present a row representing a new movie, the imageview is as likely reused as it is new.
What you want to consider is that your data array (an array of your downloaded clips, with potentially unlimited objects therein) is completely discrete from your tableview's array of cells, which is going to be a relatively small number.
My advice would be to conceive a download cache of images. Basically, as your thumbnails are downloaded, assign each a unique string id, and write the actual image file out to disk. Assign the unique ID string to your model object. When your tableview prepares to present an image, locate the image for the cell using the id string, load the image from disk, and populate the image view. As long as you're not retaining the image, the image should be released when the cell presenting it goes off-screen. You can additionally empty the cache of loaded images under low memory conditions.

If you create your own class VideoTableViewCell as a subclass of UITableViewCell and you give your cell a property for an image this image will be released as soon as the cell goes off the screen. The cell and the image will be recreated as soon as the Cell come back on the view.
For the videos I would store all downloaded video files in the documents folder and store there url in an array. If a cell comes visible or is clicked simply load the file from the hard drive.

Related

The right approach to loading dynamic content into a UITableView in iOS

ok, I've read tons of bits and pieces on the subject of loading dynamic content (from the web) into a UITableView and the problem with calculating cell height upfront. I've tried different simple implementations but the problem persists...
Assuming I need to read a JSON file from the web, parse it into 'item' objects, each with variable size image and various text labels, here is what I believe would be the right approach to avoid long hang time of the app while everything is loading:
on app load read JSON file and parse into items array
provide only small part of the items array to the tableview (about 10 items) - since I need to load the images associated with each item to calculate cell height - I don't want the view to go through the whole items list and load all images - this hangs the app until every image is loaded
display the tableview with the available cells (assuming I load a few 'spare' ones, user can even scroll to more items)
in the background using Grand Central Dispatch download images for all/some of the remaining items and then reload the tableview with the new data (repeat step 4 if item list is very long)
Step 2 above is necessary since I have no way to calculate the cell height without loading the images first, and since tableview first calculates height of all cells it may take a very long time to download all images for all items.
Would you say this is the right approach? am I missing something?
Why don't you standardize in the tableview the image size. Then you can manipulate the images as they are displayed to fit the size. Offer a way to view the image if selected. The Quartzcore framework will allow you to take your original images and size them.
I only suggest this because it would make your tableview look more appealing with uniform picture sizes than with random ones.
You're right that the show must go on, even while your data is still loading. So you'll want to design a cell that looks attractive before it has the correct image. A common approach is to ship a default image and format the cell so that looks good.
To handle the height, the tableView datasource protocol can ask you how tall a cell should be. The way to answer is, in pseudo code:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
id myModelElement = [self.myModel objectAtIndex:indexPath.row];
UIImage *image = myModelElement.image;
if (!image) image = self.placeholderImage;
return kFIXED_HEIGHT + image.size.height;
}
You're also correct that you'll want to load the images asynchronously. See my answer here for a very simple approach to that. No GCD, not even a table row reload.

Lazy Loading in UIScrollView with Data from SQLite

In my iPad application, I've made a segmented control and one segment of which -when clicked- displays a long list (about 300) with images and labels from the local SQLite database. This is taking a lot of time to load and puts the app activity to halt while it's loading all of it from the database.
Although I've applied an activity indicator for the time being, but that looks very shoddy. Can anyone tell me how to apply Lazy Loading in a way that When the button is clicked to open that view, instead of loading all the content at once, it fetches only the content that's displayed on the content initially (about 9 images with lablels).
Thanks in advance.
You should implement paging on the list. Load first 25 item and then add button ("Next 25") on tableFooterView, which will load another 25.
If you use a UITableView, you might have a better chance.
A UITableViewCell loads cells one at a time(gives you the index of the item it is trying to load), so if you use a table view, it will only load the number of items that it needs to display. You tell it how many items there are, how tall they are, etc.
It also reuses cells, so it gives a lot better performance than creating 300 different views in memory at a time.
A UIScrollView doesn't know about your "items", so it lets you push as many items as you want into a view, and then adds a scroll bar. No optimization here for memory usage, or database access.

Cocoa-Touch: Is there any open-source UIImageView subclass that supports touchUpInside and initWithUrl?

It's been more than 3 years since Cocoa-Touch is out, the licensing is permissive now.
Many, many apps have UIImageViews that are actually buttons, and load from the internet.
Is there any open UIImageView subclass (or similar) that supports:
adding a target for the touchUpInside event (maybe others too)
initializing with a NSURL, loading the image from that URL (async ofc) and displaying a UIProgressIndicatorView while loading
Or is everyone pretty much rolling their own for this?
It seems to be such a common thing, yet google has no good hits.
You wouldn't want the UIImageView derived class to load its image--especially if it's in a table view because when the user scrolls the table view, the image that will display in the image view would need to change. If you are assigning a specific image to a specific image view within a table view, you run the risk that the image displaying will be out of date by time the image data has actually returned.
While I wouldn't call it trivial as Daniel said, I would say that it is simple enough that you could probably code it up fairly quickly. The idea though is that you want to have some other class, a singleton perhaps, that handles all of your image download requests and then notifies your view that contains your image view that the images are available when the requests complete.
You should also consider that you can set an image for a UIButton, so then you wouldn't need to derive your own UIImageView if all you need is -touchUpInside. You could create an action for the button and implement it pretty easily.

Static cell from Nib file is not shown

I have a Nib file containing grouped table view and a cell. The cell is connected to UITableViewController through outlet. In cellForRowAtIndexPath I just return that cell and I can see a single cell in the table view. But when I change the row count of table to 2 and want to show the same cell, then I can see only one, it appears that the second cell is intended to be there, as the lower corners of the visible cell are not rounded, however, it's not there.
If I create a second cell object in nib file, second outlet and return it as second row, the it appears fine. My cell has identifier specified in IB.
Does it mean I can't re-use cell object for more than one row?
In the same way as you would need one instance of a UIButton for each visible button in your view, you will need one instance of your cell for each visible row.
The common pattern to manage this, is to ask the tableview for a previously instantiated cell that is no longer needed (dequeueReusableCellWithIdentifier:), and then return that cell. If the table view does not have any reusable cells, you have to instantiate a new one from your nib file.
There are many examples on this around the web, and you can also find some here at SO, ex in this answer.
I would recommend that you read through Apples TableView Programming Guide, which also contains a section on loading cells from nibs.
UPDATE:
An attempt on explaining the TableView and reuse of cells in a different way.
Lets say we have a large gallery with
old paintings. Thousands of paintings.
The gallery has just one display room,
though, and it has walls for just ten
paintings. The gallery manager has to
switch paintings now and then when the
visitors get bored and want to see
some new paintings.
Every displayed painting needs a
frame. Without a frame, it can't be
put on a wall. Frames are expensive to
make, and take up a lot of space. The
frame maker guy want have time nor
money to build the thousands of frames
needed.
He finds out that he want be needing
frames for all the paintings that is
not shown at the moment. He would only
need ten frames for the currently
displayed paintings. When the gallery
manager takes down a painting, the
frame maker stores the frame, and when
the gallery manager put up a new
painting and asks the frame maker for
a frame for it, the frame maker
returns the frame from the previous
painting again.
One day, the
needed-space-between-paintings-regulations
gets changed for no good reason. The
gallery manager is able to put up two
more pictures in the display room. He
picks two paintings from the store
room, and asks the frame maker for
frames. The frame maker has no spare
frames, and need to make two new
frames.
Now, lets say that the gallery is a TableView, and all the paintings are rows of data. The display room with space for ten visible paintings, is the screen, with space for ten visible rows. Each visible row would need a cell, just like each displayed painting would need a frame.
In the end, you shouldn't care that much about saving resources by reusing one cell. That's TableViews responsibility. It's an implementation detail of the TableView how many cells is needed and how it is used. The protocol defines how you can ask the TableView for an reusable cell, and the documentations states that you should. That should be enough. Demo projects shows that TableView can manage very large amounts of data. If your projects struggles with performance because of instantiating 10-20 cells from nib, you probably got some problems with your nib file or something. There are some discussions, though, about the performance of loading from nib versus building cells in code. It may be interesting to you.
I had some very weird behavior that sounds very much like what you are describing some time ago.
Eventually I found that the problem was that I had just added a table view cell to a xib which contains other items such as the parent table view and controller. What I had to do was create a seperate xib for each table view cell individually. I think the issue was that loading the table view cell from an incorrectly built xib was confusing the issue.
As Vegar said there are a lot of tutorials on how to do it.

iPhone Custom UITableViewCell with image after scroll

In my app UItableView with custom cells, cells with image, but in some cells has not image.
In start the place without image is white. After scrolling table in that places appears others picture. Please help to fix this problem.
although your answer is rendering a working solution, I think it is not the correct way to deal with this problem.
Imagine an NSArray with a 1,000 NSStrings in it that you want to display using a table. By showing them in a cell with a unique id for that NSString, you are basically creating a 1,000 cells! This would slow down your app. The whole idea is that cells are reused so that only 1-2 more than displayed are created.
So the correct solution: deal with it.
reuse a cell by having a unique id just for that class
reset/renew content of the cell yourself, assume dirty content
ps watch the Stanford iPhone class on tables, number 8 (around 18:50), a guy from Apple explains all this.
http://www.stanford.edu/class/cs193p/cgi-bin/index.php
Your problem here is due to the way your are using the cell queue in the UITableView, I think you are not giving each one of your cells a unique cell identifier, because of this you are experiencing that pictures swap from one cell to another.