我有一个 iOS 项目,我在自己的类中使用 ARC,但在其他库(如 ASIHTTPRequest
)中关闭了 ARC。
我使用下面的代码从网络服务器获取图像时出现大量内存泄漏:
-(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
示例代码页中的示例代码,以消除 Xcode 中的编译器警告。
我怎样才能摆脱这些内存泄漏?我似乎只在使用 block 时才得到它们。
最佳答案
您在完成 block 中引用了错误的请求变量。您应该在 block 中引用 request
(这就是您使用 __block
标识符声明它的原因)。事实上,您根本不需要声明 weakRequest
。
如果您希望将请求保存在内存中,请将其存储在您的类中的@property (retain)
中(也许是带有buildPhotoView
方法的那个)。
关于objective-c - ASIHTTPRequest 内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7735586/