异步图片加载实例

来源:互联网 发布:淘宝哪家药店是正规 编辑:程序博客网 时间:2024/05/17 06:32
////  ImageButton.h//  Taonan////  Created by zeng conggen on 11-7-13.//  Copyright 2011 __MyCompanyName__. All rights reserved.//#import <UIKit/UIKit.h>@protocol ImageButtonDelegate;@interface ImageButton : UIButton {    id<ImageButtonDelegate> delegate;    NSString * keyWords;UIImage * defaultImage;@private    NSURLConnection * connection;    NSMutableData * data;}@property (nonatomic, assign) id<ImageButtonDelegate> delegate;@property (nonatomic, retain) NSString * keyWords;@property (nonatomic, retain) NSURLConnection * connection;@property (nonatomic, retain) NSMutableData * data;@property (nonatomic, retain, setter=setDefaultImage:) UIImage * defaultImage;- (void)loadImageFromURL:(NSURL*)url;@end@protocol ImageButtonDelegate@optional- (void) imageButton:(ImageButton *)imageButton didDownloadedImage:(UIImage *)image;@end////  ImageButton.m//  Taonan////  Created by zeng conggen on 11-7-13.//  Copyright 2011 __MyCompanyName__. All rights reserved.//#import "ImageButton.h"@implementation ImageButton@synthesize delegate;@synthesize keyWords;@synthesize connection;@synthesize data;@synthesize defaultImage;- (void)dealloc {    delegate = nil;[keyWords release];        [connection cancel]; //in case the URL is still downloading    [connection release];    [defaultImage release];    [data release];     [super dealloc];}- (void)setDefaultImage:(UIImage *)image{    if ([defaultImage isEqual:image]) {        return;    }else {        [defaultImage release];        defaultImage = [image retain];        [self setBackgroundImage:defaultImage forState:UIControlStateNormal];    }}- (void)loadImageFromURL:(NSURL*)url {    if (connection!=nil) { [connection release]; } //in case we are downloading a 2nd image    if (data!=nil) { [data release]; }        NSURLRequest* request = [NSURLRequest requestWithURL:urlcachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];    connection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; //notice how delegate set to self object    //TODO error handling, what if connection is nil?}//the URL connection calls this repeatedly as data arrives- (void)connection:(NSURLConnection *)theConnection didReceiveData:(NSData *)incrementalData {    if (data==nil) { data = [[NSMutableData alloc] initWithCapacity:2048]; }     [data appendData:incrementalData];}//the URL connection calls this once all the data has downloaded- (void)connectionDidFinishLoading:(NSURLConnection*)theConnection {    //so self data now has the complete image     [connection release];    connection=nil;    //make an image view for the image    UIImage * image = [[UIImage alloc] initWithData:data];    [self setDefaultImage:image];[self setNeedsLayout];    if (delegate) {//发送通知[delegate imageButton:self didDownloadedImage:image];}        [image release];    [data release]; //don't need this any more, its in the UIImageView now    data=nil;}@end


原创粉丝点击