关于ios的同步异步加载图片

 1 void UIImageFromURL( NSURL * URL, void (^imageBlock)(UIImage * image), void (^errorBlock)(void) )
 2 {
 3     dispatch_async( dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0 ), ^(void)
 4                    {
 5                        NSData * data = [[[NSData alloc] initWithContentsOfURL:URL] autorelease];
 6                        UIImage * image = [[[UIImage alloc] initWithData:data] autorelease];
 7                        dispatch_async( dispatch_get_main_queue(), ^(void){
 8                            if( image != nil )
 9                            {
10                                imageBlock( image );
11                            } else {
12                                errorBlock();
13                            }
14                        });
15                    });
16 }

上面是块语法加载图片的方法,同步加载与异步加载的方法是:

 1     ////////下载图片////////
 2     //方法一(暴力而有效,必须下载完才进入页面)
 3     NSURL *url = [NSURL URLWithString:@"http://cc.cocimg.com/bbs/attachment/upload/07/128707.png"];
 4     UIImage *imga = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:url]];
 5     img1.image=imga;
 6     
 7     
 8     //方法二 (需要等下载完才显示,但照样可以进入页面)
 9     NSString *url2=@"http://tp1.sinaimg.cn/2122519000/50/5620445947/1";
10     UIImageFromURL( [NSURL URLWithString:url2], ^( UIImage * image )
11                    {
12                        img2.image=image;
13                        NSLog(@"%@",image);
14                    }, ^(void){
15                        NSLog(@"error!");
16                    });

读取与存储图片

 1     UIImage *bear=[UIImage imageNamed:@"小破熊.png"];
 2     
 3     //Document
 4     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
 5     
 6     
 7     /*写入图片*/
 8     //帮文件起个名
 9     NSString *uniquePath=[[paths objectAtIndex:0] stringByAppendingPathComponent:@"image.png"];
10     //将图片写到Documents文件中
11     [UIImagePNGRepresentation(bear)writeToFile: uniquePath    atomically:YES];
12 
13     /*读取入图片*/
14     //因为拿到的是个路径,所以把它加载成一个data对象
15     NSData *data=[NSData dataWithContentsOfFile:uniquePath];
16     //直接把该图片读出来
17     img3.image=[UIImage imageWithData:data];
原文地址:https://www.cnblogs.com/LoveJiaQi/p/2864231.html