Load the network picture in GCD Way (main line loads download image + Class extension mode)
Two ways to implement the Network load picture
Method 1: effect: Load the background color gray first, load the picture after two seconds
-(void) Viewdidload {
[super viewdidload];
self. View. BackgroundColor=[uicolor graycolor];
// refresh UI (Refresh ui!!! in the main thread) )--- general method
dispatch_async(dispatch_get_global_queue(dispatch_queue_priority_default , 0 ), ^{
nsstring * path=@ "http://www.sinaimg.cn/dy/slidenews/4_img/2015_12/704_1579347_ 398766.jpg ";
nsdata * data=[nsdata datawithcontentsofurl: [Nsurl urlwithstring:p Ath]];
UIImage * image=[UIImage imagewithdata:d ATA];
NSLog(@ "%@", [nsthread currentthread]);
// return to main thread
dispatch_sync(dispatch_get_main_queue(), ^{
[nsthread sleepfortimeinterval:2];
NSLog (@ "%@", [nsthread currentthread]); // Test Code --- See if the place goes back to the main thread.
Self. ImageView. image=image; // to be Image Assign Value
});
});
}
Method 2: Class extension (encapsulation Class)
#import "Uiimageview+loadimage.h"
@implementation Uiimageview (LoadImage)
-(void) Loadimagewithpath: (nsstring *) path defaultimage: (nsstring *) Dafaultpath
{
dispatch_async(dispatch_get_global_queue(dispatch_queue_priority_default , 0 ), ^{
// cannot assign a value directly to an external variable within the block , you need to turn the type
__block nsstring * str = path;
if (path==Nil)
{
Str=dafaultpath;
}
Else
{
nsdata * data=[nsdata datawithcontentsofurl: [nsurl urlwithstring:p Ath]];
UIImage * image=[UIImage imagewithdata:d ATA];
[nsthread sleepfortimeinterval:2];
// return to main thread
dispatch_sync(dispatch_get_main_queue(), ^{
Self. image=image;
});
}
});
}
@end
Import #import "Uiimageview+loadimage.h" in the viewcontroller.m file and call the class extension method
@implementation Viewcontroller
-(void) Viewdidload {
[super viewdidload];
self. View. BackgroundColor=[uicolor graycolor];
nsstring * path= @ "http://www.sinaimg.cn/dy/slidenews/4_img/2015_12/704_ 1579347_398766.jpg "
[self. ImageView loadimagewithpath:p ath defaultimage:nil];
}
In terms of the comparison between the two methods, or the method of class extension is better, if you encounter a problem that requires the network to load pictures, you can take the encapsulated class directly to use.
Load the network picture in GCD Way (main line loads download image + Class extension mode)