I use the following code to download images:
- (void)downloadImageAtUrl:(id)url
andDelegate:(id<IPServerDelegate>)delegate_ {
NSURL *correctUrl = nil;
if ([url isKindOfClass:[NSString class]])
correctUrl = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@", kHostURL, [url substringFromIndex:1]]];
else
correctUrl = url;
__block ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:correctUrl];
[imageRequestsArray addObject:request];
[request setCompletionBlock:^{
if (request.responseStatusCode == 200) {
if (delegate_ && [delegate_ respondsToSelector:@selector(didDownloadImage:atUrl:)]) {
[delegate_ didDownloadImage:request.responseData atUrl:request.url];
}
}
else {
if (delegate_ && [delegate_ respondsToSelector:@selector(failedToDownloadImageWithUrl:)]) {
[delegate_ failedToDownloadImageWithUrl:request.url];
}
}
[imageRequestsArray removeObject:request];
}];
[request setFailedBlock:^{
if (delegate_ && [delegate_ respondsToSelector:@selector(failedToDownloadImageWithUrl:)]) {
[delegate_ failedToDownloadImageWithUrl:request.url];
}
[imageRequestsArray removeObject:request];
}];
[request startAsynchronous];
}
If the delegate_ object has been deallocated the app crashes. How do I determine that the object delegate_ has been deallocated without having to create a direct reference to it? I know about __weak pointers in iOS 5, but my app must be compatible with iOS 4.3.
Ok, so I found a solution. I’m storing all the ASIHTTPRequest objects in the requests array. When any of my UIViewControllers is about to disappear (viewWillDisappear), I’m enumeration through the array and send cancel message to each of the request objects. The only inconvenience here is that those requests have to be resumed each time view appears again, but at least it’s not crashing.