iPhone - UITableView reload on scrolling - iphone

I've a UITableView and each UITableViewCell displays a unique UIImage which is fetched from internet. As we scroll the UITableView, cells are recreated and tableView: cellForRowAtIndexPath: gets called every time to configure cells. So it loads UIImages again and again from internet and scrolling is not smooth.
The solution I found for myself right now is to create NSMutableArray of all those UIImages on ViewDidLoad then load images into UITableViewCells from that NSMutableArray which is for sure giving me smooth scrolling.
My concern with my own solution is that when I keep all UIImages in NSMutableArray and those all objects are kept in memory for as long as application runs, I am most probably making inefficient use of memory.
Is there a better, more efficient way to do this which gives me smooth scrolling as well as best memory usage?

I think this example will help you..
http://kosmaczewski.net/2009/03/08/asynchronous-loading-of-images-in-a-uitableview/

Cache the downloaded images on the filesystem. When loading a cell, first ensure that a cached copy of the associated image is available, then load it using [UIImage imageWithContentsOfFile:].

You should go with array of image link instead of the image.
You should load image asynchronously so that it will improve performance of creation of the UITableviewCell.
Verify that you are using dequeueReusableCellWithIdentifier, it will give you the smoother scrolling.

Related

What is an acceptable FPS for scrolling, and what are tips for improving performance?

I see in many WWDC video's that says you want to achieve 60.0 FPS as close as possible to get a better smooth scrolling experience. I have a UIScrolLView which loads up image and a couple of table view's at once. Currently I am getting 30 FPS. This is half of what the recommended FPS. Just wondering what FPS do you guys typically get for a table view/scroll view that loads up images and other heavy stuff/rendering stuff.
Any other tips for optiziming FPS? I've spend the past week till now firing up Instruments using the time profiler, allocations, and core animation tool to optimize as much as I can.
Just to clarify a bit on what I have. I have a masonry/waterfall/pinterest style layout on the iPad. So it's not just a regular UITableView. It's a UIScrollView that fills out the whole screen, and is filled with a couple of UIView's. Each of this view has a 150x150 UIImageView and a UITableView and also it has some attributed label, drawn using Core Text. So at one glance when you see the screen, you can see 5-8 table view at one shot, each cell again has a UIImageView and then each cell renders attributed label drawn using core text.
So you can just image how deep and complicated this is. This is not just a regular table view with a UIImageView. I know how to get 60 FPS with just one UITableView in an iPhone with a UIImage. The concept is to load images asynchrounously and not to block the main thread as much as possible.
EDIT:
It seems that the problem here is the UITableView that I have inside my view.. when I remove that from the UIView I get really smooth scrolling..
I uploaded a sample project which is a simpler version of what I have, but it clearly shows the problem. The link is here
Many things affect render performance, here are some items you can check:
Profile - You said you already did this, so great job! Unfortunately profiling is often overlooked, even though it can reveal unexpected problems. In one app I was working on a calendar with different cells representing dates. At first scrolling between cells slow, which was unexpected. I thought maybe it was drawing a few cells too many. After profiling I found that [NSCalender currentCalender] was using 85% of my CPU time! After fixing that everything scrolled great!
Images - Large images put a lot of load in CoreGraphics. Scrolling especially requires a lot of draw operations to move them around. One tip is to scale images on the device as little as you can, that makes CoreGraphics' job a lot easier. If an image is twice as large as the view displaying it, resize the UIImage before displaying it in the view. iOS devices handle PNGs best. They are compressed by a tool (pngcrush) at compile time and iOS has special hardware for rendering them.
Edit: JPGs are probably a better option for photos. iOS devices have dedicated JPG decoders as well.
Custom Drawing - If possible, cutback on the amount of custom CGContext drawing you do. Lots of custom drawing has negative effects on animation speed. I would considering using an image over complex custom drawing, if possible.
Cull - Only draw things you need to. UITableView automatically unloads and loads cells as they appear, so this is done for you, but any custom CGContext drawing should only be done when that part is visible. Also automatic view shadows can be very slow in my experience.
Reuse - Use the reuse identifier on UITableView, this will allow UITableView to reuse cell objects rather than reallocating as it scrolls - look at the answer to this question. Also reuse UIImages rather than allocating multiple for the same file. imageNamed caches images automatically but imageFromContents of file does not.
Create your own - You could create your own grid view class that culls it's subviews views hidden off screen, and scrolls with lazy content loading. By writing a custom solution you can fully control the process and create a design optimized for the usage context. For most use cases you will have a hard time building something better than the Apple standard, but I have seen it done in specific cases.
Last resort - Reduce the size of the offending view (improves filtrate), break content into multiple pages, downsize images, cut out older devices that don't perform as well. I would settle for 30 FPS before sacrificing most of that stuff. Devices will continue to get faster, older devices will be eliminated, and your app will gradually get faster.
I get close to 60 fps with my UITableViewController where the table contains about 2000 cells and each cell pulls an image from the web. The trick is to lazy load the images as you need them. This sample code from Apple is pretty helpful.
The general idea is to keep the UI responsive by not blocking the main thread. Perform downloads and other time-consuming tasks on another thread.
I would do something called Lazy Loading, which doesn't load the images until they are actually seen.
Here's a great example on how to do so: http://www.cocoacontrols.com/platforms/ios/controls/mhlazytableimages
Good Luck!
What I've done is to use NSCache. I've created a small class with properties that conforms to the NSCache data protocol (its really easy to do). So what I do is create a relationship between each cell in the main table and various things worth caching: NSAttributed strings, images etc - really anything that takes work to create. I don't preload it but you could.
When you are asked to provide a cell by the tableview, look in your cache for your primary object. If there, pull all all the objects you need. If the cache does not have the object, then get the data the old fashion way, but before you finish, save it in the cache too.
This really helped me reduce "stutter" when scrolling the cell. Also, do NOT animate anything in the cell - that kills performance. Everything should be fully rendered.
Another thing to remember - make sure ever view which can be set to opaque has its property set to YES. That for sure helps the system render the cell (including the backgound view if you use one.)
EDIT:
So you provided information that included UITableViews may the root problem. So two suggestions:
1) Can you step back and figure out how to make the scrollView a single UITableView? With table headers and footers, and section headers and footers, and even the ability to essentially make a cell a floating view, can't you figure out how to rearchitect what you have?
2) So you decide no to suggestion 1. Then, do this. Think of the space used by the tableview as being a container view. Whenever the tableview is edited, take an image snapshot of it and keep this image around. As soon as the user starts to scroll, swap the tableViews out for the images. When the scrollView stops swap the UITableView back in. This of course will take some fine tuning. In fact, you could probably overlay an opaque image snapshot over the table (which will hide it and prevent it from being asked to draw itself) during scrolling.
the human eye sees at about 60 FPS, so that's why it's recommended, but 30 FPS will also appear very smooth, especially when a regular user is viewing it, as opposed to you trying to find as much to fix as possible. This is obviously dependent on how fast the scrolling goes, if the difference from frame to frame is a movement of a few pixels, 30 FPS will do just fine, but faster movement will require a higher FPS to appear smooth
There are a few things you can do in general to get better table view performance:
1) Switch to Loren Brichter's method of drawing UITableViewCell's (for lack of a better link: http://www.therefinedgeek.com.au/index.php/2010/12/21/fast-scrolling-uitableview-updates-for-ios-4-2/)
Basically, all his code does is render all your cell content as one opaque UIView, which UITableView (and CoreGraphics) can very quickly blast onto a UITableViewCell
If you don't want to do all your cell design in drawRect:, you can still use nibs, but:
Make sure every subview is marked opaque
Don't have any transparent/semi-transparent subviews
Don't have any images with an alpha channel != 1.0f.
2) Don't let UIImageView do any scaling to display your image, give it a correctly-sized UIImage
3) If you're using iOS 5 and above, you can register a nib for a particular cell identifier. That way, when you call [tableView dequeueReusableCellWithIdentifier:], you are guaranteed to get a cell. Cell allocation is faster (according to Apple), and you get to write less code:
- (void)viewDidLoad {
UINib *nib = [UINib nibWithNibName:#"MyCell" bundle:nil];
[self.tableView registerNib:nib forCellReuseIdentifier:#"MyCellIdentifier"];
}
// ...
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = #"MyCellIdentifier";
MyCell *cell = (MyCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
// Commented out code is no longer needed
//if (cell == nil) {
// cell = [[MyCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
//}
// setup cell
return cell;
}
4) Displaying images downloaded from the web
Display a default image (something to look at while the real image is downloading)
Start the download on a separate thread (hint: use GCD's dispatch_async())
When the image comes in, cache it (hint: NSCache), and display it on the cell
Do all image downloading/caching off the main thread; the only thing you should be doing on the main thread is setting the image (remember UI code HAS to be on the main thread!)
You'll probably want to write an async-capable UIImageView (or use an existing library).
Stay away from EGOImageView, even though it has async downloading, it does cache lookup (which happens to be on disk, so that means costly disk IO) on the main thread before dispatching to a background thread for the download. I used to use it, but I ended up writing my own set of classes to handle this, and it's significantly faster.
-
Just follow these, and stuff other ppl have written here, and you'll have table views that scroll like glass in no time :)
You want 60fps, but 30 fps doesn't look too terrible in actuality. But I would try to achieve 60fps for a smoother look while scrolling.
There are many Performance Improvement possibilities, that are also shown by various tutorials
While 60 FPS is the ideal, games like Halo run very prettily in 30 FPS. The battlefield chaos in Halo probably involve more surprising, rapid motion than most lists, even complex ones like yours!

Adding number of images on UIScrollView from nsdata

I have 1000 images in an array in the form of NSData.and I need to show them on scrollview when pushing a view controller.
Currently what I am doing is I am creating image from NSData and add them on scroll view. But it takes long time to push screen from previous screen.
UIImage* img = [UIImage imageWithData:[imageArray objectAtIndex:i]];
The array has NSData for 1000 images, so it takes two much time to get convert it to a uiimage. How can I reduce the time it takes?
May I ask why you don not use a UITableView, it is much more efficient as you can easily recycle cells, and it does the layout for you. I recommend this, loading images on demand, or at least keeping thumbnails in memory and swapping them out for the full size ones. It is not feasible to keep 1000 images in memory if they are larger than a thumbnail.
Alternatively, see Apple's Photoscroller in the developer site: http://developer.apple.com/library/ios/#samplecode/PhotoScroller/Introduction/Intro.html
Have a look at AQGridView. It is deriving from UIScrollView, but has cell-reusing like UITableView.

UITableViewCell not showing until scrolling

I'm having an issue where my UITableViewCell's image (I customized it into a cell with just the image) is not showing up after being downloaded unless you have scrolled down to make it invisible and scroll up to see again.
I am using HJCache for asynchronous image downloading as well as caching. What I am not sure is if this was the issue with HJCache or my UITableViewCell and how to fix it.
When the image has finished downloading (assuming the cell itself is the delegate for the asynchronous call), call [self setNeedsDisplay] which will redraw the cell. This is what happens when the cell is reloaded because of scrolling.
Well, I'm just going to answer my own question since I had found the most ridiculous solution.
After trying out various methods and headaches, I deleted the app ( + cache) from the simulator and everything seems to be working properly again.
My best guess is that the locally stored unfinished images by HJCache were messing up.
As soon as your data is finished loading, call [tableView reloadData]; This will make the tableView reload all of it's cells that are currently visible.
When you set up the cell set the image to nil. If that doesn't work set the image to a default locally stored image of the same size web if it's just completely white.

UITableView got slowly when dragging

I am new to iPhone development, and I can not understand the working principle of UITableView well.
I customize the UITableViewCell, and the cell contains imageview. In addition, I initialize the cell reusable. However, when I drag the UITableView, it scrolls slowly.
Then what should I do to process it?
If you are loading images from your applications bundle you can increase the scroll speed by making the images the exact size they need to be to fit in the UITableViewCell imageView so the device doesn't have to size them on the fly. Do this by adding smaller versions of the images in your applications bundle, or by resizing them in code as needed in a background thread.
Alternatively if this solution won't work for you, or you are loading images from the internet have a look at Lazy loading images in UITableView, a process where images are only loaded when needed and can be downloaded asynchronously.
Alternatively, you can use a prebuilt class to do your image downloading, caching and lazy loading for you like TTImageView or SDWebImage.

Stop Images Disappearing when scrolling UITableView

I have a UI Table View Controller. Each Cell Loads an image from my webserver.
If I scroll the TableView so that a particular cell scrolls out of view and then scroll back again the image for that cell has vanished and I have to wait for it to reload.
I'm guessing this is some performance/ memory management thing build into iphone?
How can I stop this behaviour?
I believe the cells in the tableview are recycled.
cache the images in memory and assign from your cache rather than loading the images directly into the tableview
I don't know if this is best practice or not but I think you could use an NSArray or NSDictionary of UIImage and load into there first and just assign references to the objects in the array.
Update
There is some code here which uses an NSMutableDictionary for the cache