开发者

saving image in UITableViewCell

I am loading an image from an API in my tableviewcell, it downloads the image everytime I scroll down the UITableView. So what is the best way to save this image and so it doesn't have to download the image again if it i开发者_开发问答s already there?

Same thing for text, how can I save the text...


If it's not very big, you can download it once and save it into user preferences (NSUserDefaults) as NSData object. Works for me.

Alternatively, you can use asynchronous requests with NSUrlConnection and implement caching in any way you like. (For example, update image only once a week.)
Moreover, even default cache settings of NSUrlConnection might work good enough.
More on caching

edit
An example of asynchronous request.

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString: url]];
URLConnectionDelegate *delegate = ...;

NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request
                                                            delegate:delegate];

if (!connection) {
  // something went wrong
}

In delegate, you mainly need methods to handle received data and to finish connection.
Assume you have NSMutableData *receivedData object.

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
  [receivedData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
  // success, do whatever you want with data

  [receivedData release];
  [connection release];
}

The link above and API documentation provide more details about delegate structure.


Look at the LazyTableImages sample application in the iOS site sample code section. It has a great example of how to download images for a table cell using NSUrlConnection asynchronous calls and storing the images (and text) in an NSMutableArray.

This sample demonstrates a multi-stage approach to loading and displaying a UITableView. It begins by loading the relevant text from an RSS feed so the table can load as quickly as possible, and then downloads the images for each row asynchronously so the UI is more responsive.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜