A lightweight IOS image cache

Source: Internet
Author: User

Our IOS apps contain a lot of images. Creating compelling views relies heavily on a large number of decorative images, all of which must first be fetched from a remote server. If you have to get each image from the server again and again every time you open the app, the user experience is definitely not good, so it's very necessary to cache the remote image locally.

Yj
Translated over 1 years ago

0 Person Top

Top translation of good Oh!

Version 1-Look for a picture and read it from disk

Our first picture cache is simple but effective. Look for every image we've ever visited from the cache, using the remote URL as the cached key value. If the local disk cache is valid, the file is read from disk and the UIImage is created and returned immediately. If no files are found on the disk, asynchronously fetches the file from the remote URL, caches it to disk, and then returns a new UIImage.

For now, this is completely satisfying for our use. But it has an unnecessary weakness: every time a cache request reads a picture from disk, performance is consumed by the access to the disk and the decoding of the picture file.

Hell Star
Translated over 1 years ago

0 Person Top

Top translation of good Oh!

version 2-Cached cache

Thankfully, Apple's uiimage has a built-in memory cache. So, you just change one line of code, and the image changes from the disk cache to the memory cache.

When you use imagenamed: Get UIImage, the first step is to check your memory to see if the image has been loaded. If so, you can get a UIImage instance without any system costs. So replace the original wording:

return [uiimage  Imagewithcontentsoffile:[self absolutepathforurl:url]]; 

We can access the memory cache at zero cost, using the following code:

return [uiimage imagenamed:[self  Relativepathforurl:url]]; 

UIImage   finds its memory cache, and if found, returns the photo with zero consumption. If not found, this photo will be loaded from disk, consuming some system performance.  

beautiful name
translated 1 years ago

0 Human top

 

top   Good translation!

Version 3--getting queues, data prefetching, and variable urging

When improving application design we yearn for more picture elements, eager for more dazzling images, bigger pictures, more pictures.

Making these large graphs as fast as possible on the screen is critical to the user experience, but simply fetching the image data in the cache every time it needs to be displayed is not going to solve the problem. Larger images take more time to load back from the network, and too many images are requested at a time to cause all images to be loaded too late. You need to carefully consider when to check if there are any picture data in the buffer and when to crawl the image from the Web. We need to pre-cache and crawl arrays.

Jiangguo
Translated 11 months ago

0 Person Top

Top translation of good Oh!

Fast queues and slow queues

We set up two queues, one serial, one parallel. Images that are required on the screen enter the parallel queue (fastqueue), and images that may be needed later enter the serial queue (Slowqueue).

In terms of UITableView implementations, this means that the table cell on the screen gets the picture from Fastqueue, and each closed screen line of the picture is preloaded from the slowqueue.

Hell Star
Translated over 1 years ago

0 Person Top

Top translation of good Oh!

now does not need to process the picture

Suppose we want to request a page of information from the server that contains 30 events back, Once these content requests come back, we can wait in line to prefetch each of these images.

-  (void) pageLoaded: (nsarray *) newevents  {        for  (sgevent *event in newevents)  {               [sgimagecache  slowgetimageforurl:event.imageurl thendo:nil];        }} 

Slowgetimageforurl: This method adds pictures to the Slowqueue queue, allowing them to be taken out of a single sheet without blocking network traffic.

Thendo: This code block is not implemented here because we don't need to do anything about the picture at the moment. All we need to do is make sure that they are in the local disk cache and are ready to use when sliding the table on the screen.

jiangguo
translated 11 months ago

1 Human top

 

top   Good translation!

now processing pictures

The tables displayed on the screen want their pictures to be displayed immediately, so it is implemented in the table cell subclass:

-  (void) SetEvent: (sgevent *) Event {        __weak  sgeventcell *me = self;        [sgimagecache  getimageforurl:event.imageurl thendo:^ (uiimage *image)  {                me.imageView.image = image;     }    ];} 

Getimageforurl: This method adds the process of capturing pictures to the fastqueue queue, meaning that they will be executed in parallel as long as the iOS system allows. If the process of grabbing a picture already exists in the Slowqueue queue, it will be moved to the Fastqueue queue, thus avoiding duplicate requests.

jiangguo
translated 11 months ago

0 Human top

 

top   Good translation!

always async

And so on, Getimageforurl: Not an async method? If you know that the picture is already in the cache, but don't want to use it immediately on the main thread? Intuition tells you that it is wrong.

Loading pictures from disk too much resources, the same unzip the picture also dues a lot of resources. You can configure and add tables during the slide, and the last thing you want to do when sliding a table is dangerous, because it blocks the main thread and there is a lag.

Use Getimageforurl: You can leave the action of the disk loading out of the main thread, so when Thendo: this code block for closing work executes, it already has a uiimage instance, so there is no danger of slipping. If the picture already exists in the local cache, the code block for the closing work will be executed at the next run cycle, and the user will not notice the difference. What they'll notice is that the slide won't be stuck.

jiangguo
translated 11 months ago

0 Human top

 

top   Good translation!

now, you don't need to do it quickly

If the user quickly slides to the bottom of the table, dozens of or hundreds of table cells appear on the screen and request the picture data to fastqueue and then quickly disappear from the screen. Suddenly this parallel queue will flood the network with a large number of picture requests that are virtually no longer needed. When the user finally stops swiping, the corresponding table cell view on the current screen will request their picture requests for those that are not urgently needed, so the network is blocked.

This is wheremovetasktoslowqueueforurl: The cause of this method.

// a table cell is going off screen-  (void) TableView: (UITableView  *) Table        didenddisplayingcell: (UITableViewCell *) cell         forrowatindexpath: (nsindexpath*) indexPath {          // we don ' T need it right now, so  move it to the slow queue                   [sgimagecache movetasktoslowqueueforurl:[[(ID) cell  event] imageurl]];} 

This ensures that only the tasks that really need to be executed quickly are available in Fastqueue. Any tasks that were previously thought to be performed quickly but are not needed are now moved to Slowqueue.

Jiangguo
Translated 11 months ago

0 Person Top

Top translation of good Oh!

Focus and selection

There are already quite a few libraries of iOS picture caches. Some of these libraries are only for some scenarios, and some libraries provide some extensibility for different scenarios. Our library is not specifically targeted for some scenarios, and there are not too many chatty features. For our users we have three basic types of focus:

Focus 1: The best frame rate

Many libraries are very focused on this point, using some highly customizable and complex methods, although the benchmarks are not conclusively shown to be effective. We find the best frame rate by these decisions:

  1. The access to the disk (and almost everything else) is removed from the main thread.

  2. Use UIImage's memory cache to avoid unnecessary disk access and image decompression.

Jiangguo
Translated 11 months ago

0 Person Top

Top translation of good Oh!

Focus 2: Make the most important image first display

Most libraries consider making queue management a concern. For our application, this is almost the most important point.

Getting the right picture to appear on the screen at the right time boils down to a simple question: "Do we need it to show up now or just a little bit?" ”。 The images that need to be displayed immediately are the parallel loading ground, and everything else is added to the serial queue. All the urgent things before, but now not urgent, will be divided from Fastqueue to Slowqueue. And when Fastqueue is working, Slowqueue is in a suspended state.

This allows images that are badly needed to be displayed to access the network separately, while also ensuring that a picture that is not badly needed to be displayed can become a badly needed picture in a moment, as it has been stored in the cache and ready for display.

jiangguo
translated 11 months ago

0 Human top

 

top   Good translation!

Focus 3: The simplest possible API

Most libraries do this. Many libraries provide a Uiimageview classification for hiding details, and many libraries make the process of capturing a picture as convenient as possible. For the three things we do often, our library has selected three main methods:

Catch a picture quickly

__weak Sgeventcell *me = self; [Sgimagecache GetImageForURL:event.imageURL thendo:^ (UIImage *image) {me.imageView.image = image;}];

Waiting in line for a picture we'll need in a minute

[Sgimagecache SlowGetImageForURL:event.imageURL Thendo:nil];

Notification cache a picture that needs to be displayed is no longer required to be displayed immediately

[Sgimagecache MoveTaskToSlowQueueForURL:event.imageURL];
Conclusion

By focusing on prefetching, queue management, removing time-consuming tasks from the main thread, and relying on the uiimage built-in memory cache, we strive to get good results from a simple package.

A few useful links
  • Sgimagecache on GitHub

  • Sgimagecache on CocoaPods

  • Sgimagecache on Cocoadocs

A lightweight IOS image cache

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.