Method 1: Load the network picture synchronously in the UI thread
- Uiimageview *headview = [[Uiimageview alloc] Initwithframe:cgrectmake (0, 0, 40, 40)];
- Nsurl *photourl = [Nsurl urlwithstring:@"Http://www.exampleforphoto.com/pabb/test32.png"];
- URL requests are actually made in the UI main thread
- UIImage *images = [UIImage imagewithdata:[nsdata datawithcontentsofurl:photourl]; //Get uiimage via network URL
- 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
- Here's how to use Nsoperationqueue to implement a loads-load image:
- -(void) Viewdidload
- {
- [Super Viewdidload];
- Nsoperationqueue *operationqueue = [[Nsoperationqueue alloc] init];
- Self.imageview = [[[Uiimageview Alloc] Initwithframe:cgrectmake ((+), [[]] autorelease];
- [Self.imageview Setbackgroundcolor:[uicolor Graycolor];
- [Self.view AddSubview:self.imageview];
- Nsinvocationoperation *op = [[Nsinvocationoperation alloc] initwithtarget:self selector: @selector (downloadimage) Object:nil];
- [Operationqueue Addoperation:op];
- }
- -(void) Downloadimage
- {
- Nsurl *imageurl = [Nsurl Urlwithstring:headimage_url];
- UIImage *image = [UIImage imagewithdata:[nsdata datawithcontentsofurl:imageurl];
- Self.imageview.image = image;
- }
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