Clear NSURLConnections hangs when controller is down

I have a controller that makes HTTP GET requests using a custom class that acts as a delegate for NSURLConnection. After it NSURLConnectioncompletes with an error or ends, the user class calls methods on the controller and passes through the object of the NSDatareceived data.

I have a problem when the controller in action is dynamically created and pushed onto the navigation controller stack. This controller makes an HTTP GET request in its method viewDidLoad. If the user quickly presses "back" on the navigation bar, this controller is disabled. If this happens before the HTTP GET request completes, the callback received NSURLConnectionwill become a method call for the dealloc'ed object, resulting in EXC_BAD_ACCESS.

What is the best approach to flushing anyone waiting NSURLConnectionsthat has been started by a controller that can actually be freed?

I have entered some operators NSLog, and it seems that my custom class used as a delegate NSURLConnectiondoes not actually receive the message dealloc. I tried to install an instance of the controller of this class on nil in viewDidUnload, and also issue a call on it, but it still lives longer than the controller.

+3
source share
3 answers

, [whateverConnection cancel] viewDidUnload dealloc. . , , , , NSURLConnection. ( ) dealloc . bool, wasCanceled, - , wasCanceled . ( , , , , - ). , . , , , .

@interface CompaniesDownloader : NSObject /*<NSXMLParserDelegate>*/
{
    id<CompaniesDownloaderDelegate> delegate; //a view controller is the delegate
    NSMutableArray *companies;

    BOOL isWorking;    
    BOOL wasCanceled;   

    @private

    //url connection object
    NSURLConnection *companiesConnection;

    //this is where i put the binary data that gets transformed into xml
    NSMutableData *webData;

    //temporary string used when parsing xml
    NSMutableString *tmpString;

    //temporary company used when parsing xml
    Company *tmpCompany;
}

:

-(void) cancel
{
  [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible: FALSE];

  wasCanceled = TRUE;
  [companiesConnection cancel];
  [webData release];
  webData = nil;
  self.companiesConnection = nil; //OR [companiesConnection release]; companiesConnection=nil;
  isWorking = FALSE;
}
+2

, ,

YourViewController.m
- (void)callGetRequest {
   [self retain];
}

- (void)didFinishAllGetTask {
   [self release];
}
0

"" , dealloc'ed. HTTP- GET, NSURLConnection dealloc'ed, EXC_BAD_ACCESS.

"", . ( , - someObject.delegate = nil;). dealloc.

0

Source: https://habr.com/ru/post/1763732/


All Articles