代码改变世界

iphone中使用NSoperation实现图片异步加载

2011-12-19 15:46  java环境变量  阅读(189)  评论(0)    收藏  举报
采用UITableView显示从网络上下载的图片,因为网络图片下载比较耗费时间,一般采用边显示文字,内容,后台下载图片,下载完成后刷新TableViewCell ,本文将演示如何通过自定的UITableViewCell,显示图片。

1。定义ImageTableViewCell 

1
2
3
4
5
6
7
8
9
@interface ImageTableViewCell : UITableViewCell {
    UILabel *txtLabel;
    UIImageView *imageView;
}
@property(nonatomic, retain)IBOutlet UILabel *txtLabel;
@property(nonatomic, retain)IBOutlet UIImageView *imageView;
 
- (void)setCell:(UIImage *)image text:(NSString *)text;
@end
方法添加如下 


 
- (void)setCell:(UIImage *)image text:(NSString *)text
{
    if(image != nil)
    {
        self.imageView.image = image;
    }
     
    self.txtLabel.text = text;
 
}
具体实现代码,请在源代码里查看

2。定义ImageDownloader ,这个类继承NSOperation,因为需要并发,所以需要实现下面4个方法 

//是否允许并发,
-(BOOL)isConcurrent 
- (BOOL)isExecuting
//是否已经完成,这个必须要重载,不然放在放在NSOperationQueue里的NSOpertaion不能正常释放。
- (BOOL)isFinished
//具体下载的方法在这里执行。

- (void)start 

而对应于非并发的情况下,只需要重载main方法就好了。


 
#import <Foundation/Foundation.h>
 
@protocol imageDownloaderDelegate;
 
@interface ImageDownloader : NSOperation
{
    NSURLRequest* _request;
     
    NSURLConnection* _connection;
     
    NSMutableData* _data;
     
    BOOL_isFinished;
     
    id<imageDownloaderDelegate> delegate;
     
    NSObject *delPara;
}
 
- (id)initWithURLString:(NSString *)url;
 
@property (readonly) NSData *data;
@property(nonatomic, assign) id<imageDownloaderDelegate> delegate;
@property(nonatomic, retain) NSObject *delPara;
 
@end
 
@protocol imageDownloaderDelegate
 
@optional
 
//图片下载完成的委托
- (void)imageDidFinished:(UIImage *)image para:(NSObject *)obj;
 
@end