1

我懒惰地将标志图像加载到具有 16 个国家/地区的 tableview 上。这是我的代码:

#import "ViewController.h"

@implementation ViewController
@synthesize tableView;
@synthesize countryNamesArray;
@synthesize receivedData; 
@synthesize flagImage;
@synthesize flagImagesArray;
@synthesize requestsAlreadyMade;

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle
-(void)issueRequest:(NSString *)fullCountryImageURL{

    NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:fullCountryImageURL]
                                              cachePolicy:NSURLRequestUseProtocolCachePolicy
                                          timeoutInterval:60.0];
    // create the connection with the request
    // and start loading the data
    NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
    if (theConnection) {
        // Create the NSMutableData to hold the received data.
        // receivedData is an instance variable declared elsewhere.
        receivedData = [NSMutableData data];                                    
    } 
    else {
        // Inform the user that the connection failed.
    }
}

- (void)viewDidLoad
{   
    requestsAlreadyMade = [[NSMutableArray alloc]init];
    flagImagesArray = [[NSMutableArray alloc]init];
    for(int x=0; x<16; x++){
        [flagImagesArray insertObject:[UIImage imageNamed: @"jollyroger_poisonflag.jpg"] atIndex:x];

    }
    countryNamesArray=[[NSArray alloc] initWithObjects:@"India",@"USA",@"Antarctica",@"Brazil",@"Canada",@"China",@"France",@"Germany",@"Italy",@"Japan",@"Kenya",@"Malaysia",@"Mexico",@"South Africa",@"United Kingdom",@"Vietnam",nil];


    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
    } else {
        return YES;
    }
}

-(NSInteger)tableView:(UITableView *)tableview numberOfRowsInSection:(NSInteger)section{
    return 16;
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    // This method is called when the server has determined that it
    // has enough information to create the NSURLResponse.

    // It can be called multiple times, for example in the case of a
    // redirect, so each time we reset the data.

    // receivedData is an instance variable declared elsewhere.
    [receivedData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    // Append the new data to receivedData.
    // receivedData is an instance variable declared elsewhere.
    [receivedData appendData:data];
}
- (void)connection:(NSURLConnection *)connectiondidFailWithError:(NSError *)error
{
    // release the connection, and the data object
    // receivedData is declared as a method instance elsewhere


    // inform the user
    NSLog(@"Connection failed! Error - %@ %@",
          [error localizedDescription],
          [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    // do something with the data
    // receivedData is declared as a method instance elsewhere
    NSLog(@"Succeeded! Received %d bytes of data",[receivedData length]);
    flagImage = [UIImage imageWithData: receivedData];
    if([receivedData length]==19935){
        for (NSIndexPath *indexPath in [tableView indexPathsForVisibleRows]){
            if(indexPath.row==0)
                [flagImagesArray replaceObjectAtIndex:0 withObject:flagImage];
        }
    }
    else if([receivedData length]==9280){
        for (NSIndexPath *indexPath in [tableView indexPathsForVisibleRows]){
            if(indexPath.row==1)
                [flagImagesArray replaceObjectAtIndex:1 withObject:flagImage];
        }
    }
    else if([receivedData length]==9567){
        for (NSIndexPath *indexPath in [tableView indexPathsForVisibleRows]){
            if(indexPath.row==2)
                [flagImagesArray replaceObjectAtIndex:2 withObject:flagImage];
        }
    }
    else if([receivedData length]==12152){
        for (NSIndexPath *indexPath in [tableView indexPathsForVisibleRows]){
            if(indexPath.row==3)
                [flagImagesArray replaceObjectAtIndex:3 withObject:flagImage];
        }
    }
    else if([receivedData length]==10903){
        for (NSIndexPath *indexPath in [tableView indexPathsForVisibleRows]){
            if(indexPath.row==4)
                [flagImagesArray replaceObjectAtIndex:4 withObject:flagImage];
        }
    }
    else if([receivedData length]==11298){
        for (NSIndexPath *indexPath in [tableView indexPathsForVisibleRows]){
            if(indexPath.row==5)
                [flagImagesArray replaceObjectAtIndex:5 withObject:flagImage];
        }
    }
    else if([receivedData length]==8682){
        for (NSIndexPath *indexPath in [tableView indexPathsForVisibleRows]){
            if(indexPath.row==6)
                [flagImagesArray replaceObjectAtIndex:6 withObject:flagImage];
        }
    }
    else if([receivedData length]==6865){
        for (NSIndexPath *indexPath in [tableView indexPathsForVisibleRows]){
            if(indexPath.row==7)
                [flagImagesArray replaceObjectAtIndex:7 withObject:flagImage];
        }
    }
    else if([receivedData length]==10567){
        for (NSIndexPath *indexPath in [tableView indexPathsForVisibleRows]){
            if(indexPath.row==8)
                [flagImagesArray replaceObjectAtIndex:8 withObject:flagImage];
        }
    }
    else if([receivedData length]==9423){
        for (NSIndexPath *indexPath in [tableView indexPathsForVisibleRows]){
            if(indexPath.row==9)
                [flagImagesArray replaceObjectAtIndex:9 withObject:flagImage];
        }
    }
    else if([receivedData length]==8962){
        for (NSIndexPath *indexPath in [tableView indexPathsForVisibleRows]){
            if(indexPath.row==10)
                [flagImagesArray replaceObjectAtIndex:10 withObject:flagImage];
        }
    }
    else if([receivedData length]==12238){
        for (NSIndexPath *indexPath in [tableView indexPathsForVisibleRows]){
            if(indexPath.row==11)
                [flagImagesArray replaceObjectAtIndex:11 withObject:flagImage];
        }
    }
    else if([receivedData length]==5980){
        for (NSIndexPath *indexPath in [tableView indexPathsForVisibleRows]){
            if(indexPath.row==12)
                [flagImagesArray replaceObjectAtIndex:12 withObject:flagImage];
        }
    }
    else if([receivedData length]==10562){
        for (NSIndexPath *indexPath in [tableView indexPathsForVisibleRows]){
            if(indexPath.row==13)
                [flagImagesArray replaceObjectAtIndex:13 withObject:flagImage];
        }
    }
    else if([receivedData length]==9690){
        for (NSIndexPath *indexPath in [tableView indexPathsForVisibleRows]){
            if(indexPath.row==14)
                [flagImagesArray replaceObjectAtIndex:14 withObject:flagImage];
        }
    }
    else if([receivedData length]==11590){
        for (NSIndexPath *indexPath in [tableView indexPathsForVisibleRows]){
            if(indexPath.row==15)
                [flagImagesArray replaceObjectAtIndex:15 withObject:flagImage];
        }
    }


    [tableView reloadData];
}



-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellIdentifier = @"countryCell";
    static int numberOfRequests=0;
    UITableViewCell *cell=(UITableViewCell *) [self.tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell==nil){
        cell=[[UITableViewCell alloc] initWithStyle: UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
    }

    // Create the request.

    NSString *flagImageURLPartOne = @"http://www.imageslink/";
    NSString *countryNumber = [NSString stringWithFormat:@"%i", indexPath.row+1];
    NSString *flagImageURLPartTwo = @".png";
    NSString *fullCountryImageURL = [NSString stringWithFormat:@"%@%@%@", flagImageURLPartOne, countryNumber, flagImageURLPartTwo];
    if(!([requestsAlreadyMade containsObject:fullCountryImageURL])){
         [self issueRequest:fullCountryImageURL];
         [requestsAlreadyMade addObject:fullCountryImageURL];
    }



    cell.imageView.image=[flagImagesArray objectAtIndex:indexPath.row];
    cell.textLabel.text= [countryNamesArray objectAtIndex:indexPath.row];

    return cell;
}

-(void) tableView:(UITableView *) tableview didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
}


@end

所以我遇到的问题有点奇怪。当 tableview 首次加载时,初始可见行加载得很好。如果我快速向下滚动到列表的后半部分,所有其他图像延迟加载也很好。但是,如果我非常缓慢地向下滚动,即使在我停止滚动之后,我的国家的一张图片也永远不会加载。有没有人有任何想法可能导致这种情况?

4

1 回答 1

0

我可以通过更改“(void)connectionDidFinishLoading:(NSURLConnection *)connection”方法中的代码来解决此问题,以检查基于方法 [NSURLConnection currentRequest] 而不是按大小下载的图像。这将代码简化为只有一个 if 语句和循环,我认为这提高了我需要防止不稳定的性能。

于 2012-10-12T01:27:01.157 回答