2010-09-14 40 views
1

如何让这段代码异步?在iphone上下载asynchoronus图像

,因为这代码允许的ImageView改变自来水形象,但现在它的慢

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

    NSUInteger sections = [indexPath section]; 

    if (sections == 3) 
    { 
     ltxt.text = [NSString stringWithFormat:@" %d of %d", tap,[a1 count]]; 


     if(tap<[a1 count]-1) { 

      tap++; 

    NSString *sa=[a1 objectAtIndex:tap]; 

      image= [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat: sa,[a1 objectAtIndex:tap ]]]]]; 


      // NSData *imageData = [NSData dataWithData:UIImageJPEGRepresentation(image, 1.0)]; 


      myImageView.image = image; 
      //[myimg release]; 
} 

回答

1

这取决于你需要多少图像在任何给定的时间要求。我发现的一个很好的解决方案是为工业强度设计/请求创建一个请求漏斗(减少图像数量)。这些请求支持取消(当图像视图离开屏幕时),并且都通过NSOperationQueue处理。有很多线程工作(读取:不是为了noob),以使其无缝连接,但对于有大量图像的大型表格非常有用(因为对于可放入物理内存的图像数量的上限很低具有最少内存量的iOS设备)。

这是一个'正确'的方式,如果你有很多图片下载。如果没有,那么你可以使用performSelectorInBackground:...来查看实现,并让对象执行自己的锁定/处理。无论哪种方式,当图像被下载时,你都必须做些什么/显示什么,所以调用线程(通常是主线程)在图像被接收时不会被阻塞。

Q ::后续:谢谢,但我应该在哪里申报此方法?如果里面(部分== 3){} - user437503

A ::将采取的一般`”形式:

- (void)setCellImage:(UIImage *)img { 
/* assert here if called from secondary thread */ 
    myImageView.image = img; 
} 

- (void)udpateImageFollowingTap { 
    NSAutoreleasePool * pool = [NSAutoreleasePool new]; 
    NSString * imageUrl = [self.a1 objectAtIndex:self.tap]; 
    UIImage * tmpImage = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imageUrl]]]; 
    [self performSelectorOnMainThread:@selector(setCellImage:) withObject:tmpImage]; 
    [tmpImage release]; 
    [pool release]; 
} 

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 
    NSUInteger sections = [indexPath section]; 
    if (sections == 3) { 
     ltxt.text = [NSString stringWithFormat:@" %d of %d", tap,[a1 count]]; 
     if(tap<[a1 count]-1) { 
      tap++; 
      /* insert code to discard previous image and display loading image indication here */ 
      [self performSelectorInBackground:@selector(udpateImageFollowingTap) withObject:0]; 
     } 
    } 
} 
+0

如果需要每个分接头/用户事件的一个图像,然后使用方法performSelectorInBackground将是首选。 – justin 2010-09-14 05:18:55

+0

谢谢,但我应该在哪里申报此方法?在内部如果(部分== 3) {} – prajakta 2010-09-14 06:11:09

+0

谢谢,但我得到这个错误[BookDetailViewController performSelectorOnMainThread:withObject:]:无法识别选择发送到实例0x1ab8f0 我认为[self performSelectorOnMainThread:@selector(setCellImage :) withObject:tmpImage] ; 是错的 – prajakta 2010-09-14 06:49:56