通过NSURLConnection异步加载TableView图像

时间:2012-10-08 18:51:00

标签: iphone objective-c ios

正如标题所暗示的那样,我试图通过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

有人有什么想法吗?

1 个答案:

答案 0 :(得分:1)

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

查看tableView:cellForRowAtIndexPath:中发生的情况您异步发出图像请求,然后将当前flagImage分配给单元格的图像视图。但NSURLConnection委托方法在未来的某些非确定性时间触发,当时重新分配flagImage

您当前在tableView:cellForRowAtIndexPath:中所做的工作将适用于同步NSURLConnection,但您会被异步委托回调绊倒。

相关问题