ASIHTTPRequest Asynchronous Crash When Changing Views
I'm using ASIHttpRequest to recieve data from an xml file. However during an asynchronous request as soon as i change the view (back to the previous view using the navigation controller) the application crashes with a EXC_BAD_ACCESS on the main.m
This only happens while the request is being made.
Below is my code:
-(void)ProcessXML{
//Set url from string to url
NSURL *theurl = [NSURL URLWithString:@"http://twitter.com/statuses/user_timeline/2smssupport.xml"];
asirequest = [ASIHTTPRequest requestWithURL:theurl];
[asirequest setDelegate:self];
[asirequest startAsynchronous];
}
- (void)requestFinished:开发者_运维知识库(ASIHTTPRequest *)request
{
NSLog(@"Saving to Defaults");
NSData *responseData = [request responseData];
xmlSaved = responseData;
prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:responseData forKey:@"xmlDownload"];
rssParser = [[RssParser alloc] loadXMLbyURL:xmlSaved];
[self.tableView reloadData];
NSLog(@"%@",[prefs dataForKey:@"xmlDownload"]);
}
The Process XML method triggers the request and the then received data is processed in the RequestFinished.
There must be something i'm missing with the ASIHTTPRequest but i don't know what it is?
Thanks
This block of code should fix it:
-(void) viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
[request clearDelegatesAndCancel]
}
If the view is being release then the delegate you set on the request is now invalid. Make sure you set the delegate to nil on the view dealloc and also stop the request.
The asirequest
object isn't being retained anywhere, so it's being deallocated after ProcessXML
returns.
NSZombieEnabled helps you a lot. You can tell which object is causing EXC_BAD_ACCESS.
Are you deallocating the ASIHTTPRequest
object when you leave the current view? My guess is that the delegate methods are being called after your view controller has been released.
--
@Simon is right that you do need to set the delegate to nil. What I would do is:
- Create an
ASIHTTPRequest
property in your class and set that property in yourProcessXML
method. This simplifies memory management and ensures that the request object will stick around while you need it. - In both your
dealloc
method and yourrequestFinished
methods, set the request delegate to nil and setself.request = nil;
At the very least, you should set the delegate to nil in your requestFinished
method, but you need to remember to stop your request from running if you navigate away from this view controller before it returns, hence setting it to nil in the dealloc
method as well.
精彩评论