轉自:http://wonderzl.iteye.com/blog/696160
從網上加載圖片,當網速慢或是圖片較大時,你會發現程序可能會失去對用戶的響應.這樣你可以用多線程:
- -(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下來一次後就將圖片緩存起來,再次顯示的時候就不用去下載。
假設有多張圖片,用循環存多個路徑:
- - (void)downloadImage {
- NSString *imagePath;
- for (...)
- imagePath = [GetImage saveImage:imageUrlPath withCache:@""];
- }
需要寫GetImage類,實現剛纔的方法.
GetImage.h文件如下:
- #import <Foundation/Foundation.h>
- @interface GetImage : NSObject {
- }
- +(NSString *) saveImage:(NSString *)urlpath withCache:(NSString *)filename;
- @end
GetImage.m文件如下:
- @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]