iPhone程序中图片延时加载

本文介绍如何通过多线程、缓存机制优化图片加载速度,减少网络延迟影响,并提供了一个实例说明如何使用循环存取多张图片,以及实现缓存功能的详细步骤。通过在本地缓存图片,避免重复下载,提升用户体验。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

从网上加载图片,当网速慢或是图片较大时,你会发现程序可能会失去对用户的响应.这样你可以用多线程:

Java代码 复制代码  收藏代码iPhone程序中图片延时加载
  1. -(void) buildData {   
  2.     NSOperationQueue *queue [NSOperationQueue new];   
  3.        
  4.     [queue setMaxConcurrentOperationCount:NSOperationQueueDefaultMaxConcurrentOperationCount];   
  5.        
  6.     NSInvocationOperation *operation [[NSInvocationOperation alloc] initWithTarget:self    
  7.                                                                             selector:@selector(downloadImage)    
  8.                                                                               object:nil];   
  9.     [queue addOperation:operation];   
  10.     [operation release];   
  11.  
-(void) buildData {
        NSOperationQueue *queue = [NSOperationQueue new];
        
        [queue setMaxConcurrentOperationCount:NSOperationQueueDefaultMaxConcurrentOperationCount];
        
        NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self 
                                                                                                                                                        selector:@selector(downloadImage) 
                                                                                                                                                          object:nil];
        [queue addOperation:operation];
        [operation release];
}



解决的方法是从网上down下来一次后就将图片缓存起来,再次显示的时候就不用去下载。
假设有多张图片,用循环存多个路径:
Java代码 复制代码  收藏代码iPhone程序中图片延时加载
  1. (void)downloadImage {   
  2.     NSString *imagePath;   
  3.     for (...)   
  4.         imagePath [GetImage saveImage:imageUrlPath withCache:@""];   
  5.  
- (void)downloadImage {
        NSString *imagePath;
        for (...)
                imagePath = [GetImage saveImage:imageUrlPath withCache:@""];
}

需要写GetImage类,实现刚才的方法.
GetImage.h文件如下:
Java代码 复制代码  收藏代码iPhone程序中图片延时加载
  1. #import    
  2.   
  3.   
  4. @interface GetImage NSObject {   
  5.        
  6. }   
  7. +(NSString *) saveImage:(NSString *)urlpath withCache:(NSString *)filename;   
  8.   
  9. @end  
#import 


@interface GetImage : NSObject {
        
}
+(NSString *) saveImage:(NSString *)urlpath withCache:(NSString *)filename;

@end


GetImage.m文件如下:
Java代码 复制代码  收藏代码iPhone程序中图片延时加载
  1. @implementation GetImage   
  2. +(NSString *) saveImage:(NSString *)urlpath withCache:(NSString *)filename   
  3. {   
  4.     NSData *retureData=nil;   
  5.     NSAutoreleasePool *pool=[[NSAutoreleasePool alloc] init];   
  6.     NSFileManager *fileManager [NSFileManager defaultManager];   
  7.     NSArray *cache NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);   
  8.     NSString *cachePath [cache objectAtIndex:0]    
  9.     filename=[filename stringByAppendingFormat:@"%@",[urlpath lastPathComponent]];   
  10.     NSString *filepath [cachePath stringByAppendingString:@"/"];             
  11.     filepath=[filepath stringByAppendingString:filename];   
  12.        
  13.     NSLog(@"filepath=%@",filepath);   
  14.     BOOL success;   
  15.     success [fileManager fileExistsAtPath:filepath];   
  16.     if (success)    
  17.     {   
  18.         return   filepath;   
  19.            
  20.     }   
  21.     else  
  22.     {   
  23.         NSMutableURLRequest *request [[[NSMutableURLRequest alloc] init] autorelease];     
  24.         [request setURL:[NSURL URLWithString:urlpath]];     
  25.         [request setHTTPMethod:@"GET"];     
  26.            
  27.         NSURLResponse *response;   
  28.         NSError *error;   
  29.            
  30.         retureData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];   
  31.            
  32.         if ([fileManager createDirectoryAtPath:cachePath attributes:nil]==NO){   
  33.             ////NSLog(@"fileManager createDirectoryAtPath:cachePath attributes:nil");   
  34.         }   
  35.         if ([retureData writeToFile:filepath atomically:YES]){   
  36.             NSLog(@"save Image Success");   
  37.         }   
  38.         else  
  39.         {   
  40.             NSLog(@"save Image Fail");   
  41.         }   
  42.     }   
  43.        
  44.     if (retureData !=nil && [fileManager fileExistsAtPath:filepath]){   
  45.            
  46.         return   filepath;   
  47.     }   
  48.     [pool release];   
  49.        
  50.     NSLog(@" Image return nil");   
  51.     return nil;   
  52.        
  53.        
  54.        
  55.  
@implementation GetImage
+(NSString *) saveImage:(NSString *)urlpath withCache:(NSString *)filename
{
        NSData *retureData=nil;
        NSAutoreleasePool *pool=[[NSAutoreleasePool alloc] init];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSArray *cache = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
        NSString *cachePath = [cache objectAtIndex:0] ; 
        filename=[filename stringByAppendingFormat:@"%@",[urlpath lastPathComponent]];
        NSString *filepath = [cachePath stringByAppendingString:@"/"];                  
        filepath=[filepath stringByAppendingString:filename];
        
        NSLog(@"filepath=%@",filepath);
        BOOL success;
        success = [fileManager fileExistsAtPath:filepath];
    if (success) 
        {
                return   filepath;
                
        }
        else
        {
                NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];  
                [request setURL:[NSURL URLWithString:urlpath]];  
                [request setHTTPMethod:@"GET"];  
                
                NSURLResponse *response;
                NSError *error;
                
                retureData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
                
                if ([fileManager createDirectoryAtPath:cachePath attributes:nil]==NO){
                        ////NSLog(@"fileManager createDirectoryAtPath:cachePath attributes:nil");
                }
                if ([retureData writeToFile:filepath atomically:YES]){
                        NSLog(@"save Image Success");
                }
                else
                {
                        NSLog(@"save Image Fail");
                }
        }
        
        if (retureData !=nil && [fileManager fileExistsAtPath:filepath]){
                
                return   filepath;
        }
        [pool release];
        
        NSLog(@" Image return nil");
        return nil;
        
        
        
}


至此,存储完毕,在用的时候调用刚才存的路径就可以了,可用方法[[UIImage alloc] initWithContentsOfFile:imagePath] 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值