#import "ImagesViewController.h"
#import "InternetResource.h"
#define SOME_RESOURCE_URL @"http://media.wiley.com/product_data/coverImage/28/04707428/0470742828.jpg"
#define BAD_RESOURCE_URL2 @"http://media.wiley.com/product_data/coverImage/5.jpg"
@implementation ImagesViewController
@synthesize iResources;
- (id)initWithStyle:(UITableViewStyle)style {
if (self = [super initWithStyle:style]) {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleFinishedLoading:) name:FinishedLoading object:nil];
self.iResources = [NSArray arrayWithObjects:
[[[InternetResource alloc] initWithTitle:@"First pic" andURL:BAD_RESOURCE_URL2] autorelease],
[[[InternetResource alloc] initWithTitle:@"Second pic" andURL:SOME_RESOURCE_URL] autorelease],
[[[InternetResource alloc] initWithTitle:@"Third pic" andURL:SOME_RESOURCE_URL] autorelease],
[[[InternetResource alloc] initWithTitle:@"Fourth pic" andURL:SOME_RESOURCE_URL] autorelease],
[[[InternetResource alloc] initWithTitle:@"Fifth pic" andURL:SOME_RESOURCE_URL] autorelease],
[[[InternetResource alloc] initWithTitle:@"Sixth pic" andURL:SOME_RESOURCE_URL] autorelease],
nil];
}
return self;
}
-(void)handleFinishedLoading:(NSNotification*)notification{
[self performSelectorOnMainThread:@selector(reloadTheData:) withObject:notification.object waitUntilDone:NO];
}
-(void)reloadTheData:(InternetResource*)_resource{
[self.tableView reloadData];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.iResources.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return 140;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
InternetResource *iResource = [self.iResources objectAtIndex:indexPath.row];
cell.textLabel.text = iResource.title;
cell.imageView.image = nil;
@synchronized(iResource){
switch (iResource.status) {
case NEW:
cell.imageView.image = [UIImage imageNamed:@"loading.png"];
[iResource start];
break;
case COMPLETE:
cell.imageView.image = iResource.image;
break;
case FAILED:
cell.imageView.image = [UIImage imageNamed:@"failed.png"];
break;
case FETCHING:
cell.imageView.image = [UIImage imageNamed:@"loading.png"];
break;
default:
cell.imageView.image = nil;
break;
}
}
return cell;
}
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
self.iResources = nil;
[super dealloc];
}
@end