2011-10-12 38 views
2

我有一个iOS项目,我在自己的课程中使用ARC,但在其他库如ASIHTTPRequest中关闭了ARC。ASIHTTPRequest内存泄漏

-(void)buildPhotoView { 

self.photoLibView.hidden = NO; 

NSString *assetPathStr = [self.cellData objectForKey:@"AssetThumbPath"]; 

// get the thumbnail image of the ocPHOTOALBUM from the server and populate the UIImageViews 
NSURL *imageURL = [NSURL URLWithString:assetPathStr]; 

__block ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:imageURL]; 
__unsafe_unretained ASIHTTPRequest *weakRequest = request; 
[weakRequest setCompletionBlock:^{ 

    // put image into imageView when request complete 
    NSData *responseData = [weakRequest responseData]; 
    UIImage *photoAlbumImage = [[UIImage alloc] initWithData:responseData]; 
    self.photo1ImageView.image = photoAlbumImage; 
}]; 
[weakRequest setFailedBlock:^{ 
    NSError *error = [request error]; 
    NSLog(@"error geting file: %@", error); 
}]; 
[weakRequest startAsynchronous]; 

}

我修改从ASIHTTPRequest示例代码页的样例代码:

我使用下面的代码来从一个Web服务器的图像获取巨大的内存泄漏消除Xcode中的编译器警告。

我该如何摆脱这些内存泄漏?我只是在使用块时才会得到它们。

+0

使用autoreleased对象实例化'photoAlbumImage'是否会减少泄漏的大小?即'photoAlbumImage = [UIImage imageWithData:responseData];' – FluffulousChimp

+0

使用自动引用计数时不能使用autoRelease。当我使用ASIHTTPRequest而没有使用块时,我没有得到内存泄漏,但我需要这种情况,因为我正在对图像执行多个请求,每个请求都会进入tableCell中的不同UIImageView。使用块,我可以在请求中包含一个完成块,在请求完成时将图像放入正确的UIImageView。 – Alpinista

回答

7

您正在从完成块内引用错误的请求变量。您应该在块中引用request(这就是为什么您使用__block标识符声明它的原因)。实际上,你根本不需要声明weakRequest

如果要将请求保存在内存中,请将其存储在您的班级中的@property (retain)(也许是buildPhotoView方法中的那个)。

+0

我声明weakRequest,因为Xcode显示警告:自动引用计数问题:在此块中强烈捕获'请求'可能会导致保留周期。当我不声明weakRequest时,我得到相同数量的错误。 – Alpinista

+2

哦。在这种情况下,前缀'request'带有'__unsafe_unretained'和'__block'。 – darvids0n

+0

FWIW我试过使用:'__block __unsafe_unretained ASIHTTPRequest * request' - 它在调试模式下工作,但我在生产中崩溃! - 问题是,当启用目标c优化时,一旦尝试访问'request',此代码就会崩溃,所以如果它是对请求对象的唯一引用,请不要同时使用'__unsafe_unretained __block'! :) – herbert