iOS uiimageview loading network pictures asynchronously

Source: Internet
Author: User

Method 1: Load the network picture synchronously in the UI thread

    1. Uiimageview *headview = [[Uiimageview alloc] Initwithframe:cgrectmake (0, 0, 40, 40)];
    2. Nsurl *photourl = [Nsurl urlwithstring:@"Http://www.exampleforphoto.com/pabb/test32.png"];
    3. URL requests are actually made in the UI main thread
    4. UIImage *images = [UIImage imagewithdata:[nsdata datawithcontentsofurl:photourl]; //Get uiimage via network URL
    5. Headview.image = images;

This is the simplest, but because it is loaded in the main thread, it blocks the main thread of the UI. So you can try Nsoperationqueue, a nsoperationqueue operation queue, which is equivalent to a thread manager, not a thread. Because you can set the number of threads that can run in parallel in this thread manager, and so on.

Method 2: Use Nsoperationqueue to load asynchronously

  1. Here's how to use Nsoperationqueue to implement a loads-load image:
  2. -(void) Viewdidload
  3. {
  4. [Super Viewdidload];
  5. Nsoperationqueue *operationqueue = [[Nsoperationqueue alloc] init];
  6. Self.imageview = [[[Uiimageview Alloc] Initwithframe:cgrectmake ((+), [[]] autorelease];
  7. [Self.imageview Setbackgroundcolor:[uicolor Graycolor];
  8. [Self.view AddSubview:self.imageview];
  9. Nsinvocationoperation *op = [[Nsinvocationoperation alloc] initwithtarget:self selector: @selector (downloadimage) Object:nil];
  10. [Operationqueue Addoperation:op];
  11. }
  12. -(void) Downloadimage
  13. {
  14. Nsurl *imageurl = [Nsurl Urlwithstring:headimage_url];
  15. UIImage *image = [UIImage imagewithdata:[nsdata datawithcontentsofurl:imageurl];
  16. Self.imageview.image = image;
  17. }

However, this design, though asynchronous, does not have a cached picture. Reloading and re-reading pictures from the network, repeating the request, is not scientific, so you can consider the first request to save the picture.

iOS uiimageview loading network pictures asynchronously

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.