-2

我的项目基于评级图片。我想知道从链接中快速在 imageview 中显示图像的最佳方法,而不会出现内存泄漏和任何崩溃。因为,将来图像可能会达到数十万个,我将不得不显示这些图像。需要先下载图片吗???如果有人对此有所了解,请为我提供一些解决方案。

提前感谢大家。

4

1 回答 1

0

You can download the pictures asynchronously from the internet, which keeps the App responsive. There is already a solution for that, for example by calling the method

[yourAsynchronousImageView loadImageFromURLString:@"http://your.url/image.jpg"];

in

#import <UIKit/UIKit.h>

@interface AsynchronousImageView : UIImageView {
    NSURLConnection *connection;    
    NSMutableData *data;
    bool loading;
}  

@property bool loading;

- (void)loadImageFromURLString:(NSString *)theUrlString;

@end

and

#import "AsynchronousImageView.h"

@implementation AsynchronousImageView
@synthesize loading;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

- (void)loadImageFromURLString:(NSString *)theUrlString{ 
    self.image = nil;
    NSURLRequest *request = [NSURLRequest requestWithURL:
                             [NSURL URLWithString:theUrlString]
                                             cachePolicy:NSURLRequestReturnCacheDataElseLoad
                                         timeoutInterval:30.0];                          
    connection = [[NSURLConnection alloc]
                  initWithRequest:request delegate:self];
    loading=true;
}

- (void)connection:(NSURLConnection *)theConnection
    didReceiveData:(NSData *)incrementalData {    if (data == nil)
        data = [[NSMutableData alloc] initWithCapacity:2048];                 

    [data appendData:incrementalData];}

- (void)connectionDidFinishLoading:(NSURLConnection *)theConnection {    
    self.image = [UIImage imageWithData:data];
    data = nil; 
    connection = nil;
    loading=false;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

@end
于 2012-06-13T12:08:54.503 回答