代码之家  ›  专栏  ›  技术社区  ›  Piero

UIImageView+AFNetworking类别与UIActivityIndicatorView参考内存是否保留?

  •  0
  • Piero  · 技术社区  · 10 年前

    我正在尝试实现一个类别,以显示 UIImageView 从带有褪色和 UIActivityIndicatorView ,我在网上找到了一些东西,并在最终版本中进行了编辑:

    UIImageView+AF网络负载.m

    @implementation UIImageView (AFNetworkingLoad)
    
    - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholderImage fadeInWithDuration:(CGFloat)duration withLoadIndicator:(UIActivityIndicatorView *)load_indicator {
    
        [load_indicator startAnimating];
    
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
        [request setHTTPShouldHandleCookies:NO];
        [request addValue:@"image/*" forHTTPHeaderField:@"Accept"];
    
        __weak typeof (self) weakSelf = self;
    
        [self setImageWithURLRequest:request placeholderImage:placeholderImage success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
            [load_indicator stopAnimating];
            if (!request) // image was cached
                [weakSelf setImage:image];
            else
                [UIView transitionWithView:weakSelf duration:duration options:UIViewAnimationOptionTransitionCrossDissolve animations:^{
                    [weakSelf setImage:image];
                } completion:nil];
        } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
            [load_indicator stopAnimating];
        }];
    }
    

    然后我用它来定制 UITableViewCell 以这种方式:

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
    MyCell *cell = (MyCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    ...
    [cell.img_view setImageWithURL:[NSURL URLWithString:my_url] placeholderImage:nil fadeInWithDuration:0.3 withLoadIndicator:cell.load_img];
    ...
    }
    

    所有的工作都很好,现在我的问题是,这个实现传递了UIActivityIndicatorView的引用,我是否会有一些内存泄漏?还是保留问题?显然我在iOS项目中使用ARC。。。

    1 回复  |  直到 10 年前
        1
  •  0
  •   Dima    10 年前

    此类别不应导致内存泄漏。该方法将对象传递到复制的块中,以便该块暂时保留该对象,但一旦图像加载或加载失败,则应清除块,这将使对象的保留计数下降。