0
votes

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

5

5 Answers

3
votes

This block of code should fix it:

    -(void) viewWillDisappear:(BOOL)animated {
        [super viewWillDisappear:animated];
        [request clearDelegatesAndCancel]
     }
1
votes

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.

0
votes

The asirequest object isn't being retained anywhere, so it's being deallocated after ProcessXML returns.

0
votes

NSZombieEnabled helps you a lot. You can tell which object is causing EXC_BAD_ACCESS.

0
votes

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:

  1. Create an ASIHTTPRequest property in your class and set that property in your ProcessXML method. This simplifies memory management and ensures that the request object will stick around while you need it.
  2. In both your dealloc method and your requestFinished methods, set the request delegate to nil and set self.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.