I have a iOS project in which I am using ARC in my own classes, but have ARC turned off in other libraries like ASIHTTPRequest.
I’m getting huge memory leaks using the code below to fetch an image from a web server:
-(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];
}
I’ve modified the sample code from the ASIHTTPRequest example code page to eliminate compiler warnings in Xcode.
How can I get rid of these memory leaks? I only seem to get them when using blocks.
You’re referencing the wrong request variable from inside the completion block. You should reference
requestin the block (that’s why you declare it with the__blockidentifier). In fact, you shouldn’t need to declareweakRequestat all.If you want the request to be kept in memory, store it in an
@property (retain)in your class (the one with thebuildPhotoViewmethod perhaps).