首先从服务器上加载数据:
NSURL *url = [NSURL URLWithString:@“http://2.novelread.sinaapp.com/framework-sae/index.php“];
[self loadJsonData:url];
-(void) loadJsonData:(NSURL *)url
{
// dispatch_async(kGlobalQueue, ^{
// NSData *data = [NSData dataWithContentsOfURL:url];
// [self performSelectorOnMainThread:@selector(parseJsonData:) withObject:data waitUntilDone:NO];
// });
NSURLRequest *request = [NSURLRequest requestWithURL:url];
DownloadHelper *help = [[DownloadHelper alloc] initWithRequest:request];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(parseJsonData:) name:@"connectionFinished" object:help];
[[help connection] start];
}
-(void) parseJsonData:(NSNotification *)n
{
DownloadHelper* help = [n object];
NSData *data = [help receivedData];
NSError *error;
NSArray *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
if (json == nil) {
NSLog(@"json parse failed \r\n");
return;
}
for (int i=0; i < [json count]; i++) {
NSArray *s = [json objectAtIndex:i];
ShopData *shopdata = [[ShopData alloc] init];
shopdata._id = [s objectAtIndex:0];
shopdata.name = [s objectAtIndex:1];
shopdata.url = [s objectAtIndex:2];
shopdata.info = [s objectAtIndex:3];
[self.myArray addObject:shopdata];
[shopdata release];
}
[self.tableView reloadData];
}
[["1","book","http://novelread-file.stor.sinaapp.com/book.png","Book"],["2","cunshangcunshu","http://novelread-file.stor.sinaapp.com/cunshangcunshu.png","村上"]]
然后使用
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [myArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *TableViewDynamicLoadIdentifier = @"TableViewDynamicLoadIdentifier";
UITableViewCell *pCell = [tableView dequeueReusableCellWithIdentifier:TableViewDynamicLoadIdentifier];
if (pCell == nil)
{
pCell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:TableViewDynamicLoadIdentifier] autorelease];
pCell.selectionStyle = UITableViewCellSelectionStyleNone;
}
NSInteger nRow = [indexPath row];
ShopData *shopdata = [self.myArray objectAtIndex:nRow];
pCell.textLabel.text = shopdata.name;
pCell.detailTextLabel.text = shopdata.info;
if (shopdata.appIcon) {
pCell.imageView.image = shopdata.appIcon;
}else{
if (self.tableView.dragging == NO && self.tableView.decelerating == NO)
{
[self startIconDownload:shopdata forIndexPath:indexPath];
}
pCell.imageView.image = [UIImage imageNamed:@"Placeholder"];
}
return pCell;
}
为了解决tableview用手往下拨的时候,图片能顺利加载,必须实现协议 UIScrollViewDelegate
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
if (!decelerate)
{
[self loadImagesForOnscreenRows];
}
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
[self loadImagesForOnscreenRows];
}
- (void)loadImagesForOnscreenRows
{
if ([self.shopList count] > 0)
{
NSArray *visiblePaths = [self.myTableView indexPathsForVisibleRows];//取得tableview可见的item
for (NSIndexPath *indexPath in visiblePaths)
{
Shop *shop = [self.shopList objectAtIndex:indexPath.row];//得到tableview这个item对应的shop信息
if (!shop.shopIcon) // avoid the app icon download if the app already has an icon
{
[self startIconDownload:shop forIndexPath:indexPath];//将indexPath作为key,去下载图片
}
}
}
}
-(void)startIconDownload:(ShopData *)shopdata forIndexPath:(NSIndexPath *)indexPath{
IconDownloader *iconDownloader = [imageDownloadProgress objectForKey:indexPath];
if (iconDownloader == nil)
{
iconDownloader = [[IconDownloader alloc] init];
iconDownloader.appRecord = shopdata;
iconDownloader.indexPathInTableView = indexPath;
iconDownloader.delegate = self;
[imageDownloadProgress setObject:iconDownloader forKey:indexPath];
[iconDownloader startDownload];
[iconDownloader release];
}
}
-(void)appImageDidLoad:(NSIndexPath *)indexPath{
IconDownloader *iconDownloader = [imageDownloadProgress objectForKey:indexPath];
if (iconDownloader != nil)
{
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:iconDownloader.indexPathInTableView];
// Display the newly loaded image
cell.imageView.image = iconDownloader.appRecord.appIcon;
}
}
以下是IconDownloader的实现:
- (void)startDownload
{
self.activeDownload = [NSMutableData data];
// alloc+init and start an NSURLConnection; release on completion/failure
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:
[NSURLRequest requestWithURL:
[NSURL URLWithString:appRecord.url]] delegate:self];
self.imageConnection = conn;
[conn release];
}
- (void)cancelDownload
{
[self.imageConnection cancel];
self.imageConnection = nil;
self.activeDownload = nil;
}
#pragma mark -
#pragma mark Download support (NSURLConnectionDelegate)
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[self.activeDownload appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
// Clear the activeDownload property to allow later attempts
self.activeDownload = nil;
// Release the connection now that it's finished
self.imageConnection = nil;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// Set appIcon and clear temporary data/image
UIImage *image = [[UIImage alloc] initWithData:self.activeDownload];
if (image.size.width != kAppIconHeight && image.size.height != kAppIconHeight)
{
CGSize itemSize = CGSizeMake(kAppIconHeight, kAppIconHeight);
UIGraphicsBeginImageContext(itemSize);
CGRect imageRect = CGRectMake(0.0, 0.0, itemSize.width, itemSize.height);
[image drawInRect:imageRect];
self.appRecord.appIcon = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
}
else
{
self.appRecord.appIcon = image;
}
self.activeDownload = nil;
[image release];
// Release the connection now that it's finished
self.imageConnection = nil;
// call our delegate and tell it that our icon is ready for display
[delegate appImageDidLoad:self.indexPathInTableView];
}
运行后的图是: