我正试图实现一个类别来显示一个UIImageView
从一个褪色的url和一个UIActivityIndicatorView
,我在网上找到了一些东西,我在这个最终版本中编辑:
UIImageView + AFNetworkingLoad.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…
此类别不应导致内存泄漏。该方法将对象传递到一个复制的块中,因此它将被该块暂时保留,但是一旦图像加载或加载失败,应该清除块,这将使对象的保留计数下降。