0

正如标题所暗示的,我正在尝试通过 NSURLConnection 异步加载 tableview 图像。这里的问题是,当我向下滚动时,我的 tableview 倾向于在 tableview 中为多个国家/地区加载相同的标志图像,然后在滚动时为多个国家/地区加载不同的标志图像(因为在多个国家/地区具有相同的标志图像)备份。我注意到,只有当我滚动得很慢时,我才能获得不同国家/地区的不同旗帜图像,但图像不正确。我不太确定目前的问题是什么。这是我的代码:

#import "ViewController.h"

@implementation ViewController
@synthesize tableView;
@synthesize countryNamesArray;
@synthesize receivedData; 
@synthesize flagImage;
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{   
    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 *)connection
  didFailWithError:(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];
}

-(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.
    }
}

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

    // Create the request.


    NSString *flagImageURLPartOne = @"http://www.flagimage.com/";
    NSString *countryNumber = [NSString stringWithFormat:@"%i", indexPath.row+1];
    NSString *flagImageURLPartTwo = @".png";
    NSString *fullCountryImageURL = [NSString stringWithFormat:@"%@%@%@", flagImageURLPartOne, countryNumber, flagImageURLPartTwo];

    [self issueRequest:fullCountryImageURL];

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

    return cell;
}

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


@end

有人有想法么?

4

1 回答 1

1

不知何故,您必须flagImage通过数据结构将 与国家名称相关联。

看看在tableView:cellForRowAtIndexPath: 你异步触发图像请求中发生了什么,然后将电流分配给flagImage单元格的图像视图。但是NSURLConnection委托方法在未来某个不确定的时间触发,flagImage在那个时候重新分配。

您当前正在执行的操作tableView:cellForRowAtIndexPath:适用于同步NSURLConnection,但您会被异步委托回调绊倒。

于 2012-10-08T19:01:36.547 回答