代码之家  ›  专栏  ›  技术社区  ›  Dan Ray

一个方便的内存管理类来做异步web请求

  •  2
  • Dan Ray  · 技术社区  · 16 年前

    受苹果的LazyTables示例的启发,我刚刚为自己构建了一个名为ImageLoader的类。我太聪明了。当我非常聪明的时候,我经常会遇到这样的情况,在如何处理这个物体的记忆方面,我遇到了我智慧的极限。

    它是从viewDidLoad中的UIViewController子类实例化的,因此:

    ImageDownloader *downloader = [[ImageDownloader alloc] init];
    [downloader startDownloadWithImageView:self.theImageView
                               andImageURL:[NSURL URLWithString:myUrlString]];
    

    在ImageDownloader的方法中,我说:

    -(void)startDownloadWithImageView:(UIImageView *)imageView
                          andImageURL:(NSURL *)url
    {
     self.theImageView = imageView;
     [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
     self.activeDownload = [NSMutableData data];
    
     NSURLConnection *conn = [[NSURLConnection alloc]
      initWithRequest:[NSURLRequest requestWithURL:url] delegate:self];
     self.imageConnection = conn;
     [conn release];
    }
    

    作为NSURLConnectionDelegate,我的委托方法是(在相关部分):

    - (void)connectionDidFinishLoading:(NSURLConnection *)connection
    {  
     UIImage *image = [[UIImage alloc] initWithData:self.activeDownload];
     theImageView.image = image;
     [image release];
    }
    

    所以问题是。。。如何释放 downloader autorelease 从我创建它的ViewController,因为我不希望NSURLConnection在run循环结束时调用它的委托。我可以释放吗 self connectionDidFinishLoading ? 我从来没有见过这样做,觉得有点奇怪,释放自己在一个自己的方法。

    我的另一个想法是,我可以让它成为一个单独的,只是不担心它会一直存在,直到我们终止。但我宁愿让这个物体复活,然后干干净净地离开。

    顺便说一句,我聪明的下一步是将此功能添加为UIImageView的一个类别。打电话来会很方便的 [imageView asynchronouslyLoadImageFromURL:(NSURL *)url] .

    1 回复  |  直到 12 年前
        1
  •  2
  •   Jeff Kelley    16 年前

    你总是可以放一个 [self retain] -startDownloadWithImageView:andImageURL: 方法和步骤 [self release] 在 -connectionDidFinishLoading: 方法。很明显,这是非常规的,但是这将允许您在创建它之后自动释放它,而不用担心它过早地被杀死。