CancelPreviousPerformRequestWithTarget does not cancel my previously deferred thread started with performSelector

I started the delayed stream using performSelector , but the user still has the ability to click the back button on the current view, which calls dealloc. When this happens, my stream still seems to be callable, which causes my application to crash because the properties that the stream is trying to write have been released. To solve this problem, I am trying to call cancelPreviousPerformRequestsWithTarget to cancel the previous request, but it does not seem to work. The following are snippets of code.

 - (void) viewDidLoad { [self performSelector:@selector(myStopUpdatingLocation) withObject:nil afterDelay:6]; } - (void)viewWillDisappear:(BOOL)animated { [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(myStopUpdatingLocation) object:nil]; } 

Am I doing something wrong here? The myStopUpdatingLocation method myStopUpdatingLocation defined in the same class that I call the execution requests.

A bit more background. The function I'm trying to implement is to search for users' location, search google for some places around that location, and display a few annotations on the map. In viewDidLoad I start updating the location using the CLLocationManager . I have a timeout after 6 seconds if I don't get the desired accuracy within the timeout, and I use performSelector to do this. What could happen is that the user clicks the back button in the view and this thread will execute, although all my properties have been released, which caused a crash.

Thanks in advance!

James

+6
multithreading iphone request-cancelling
source share
2 answers

I found my problem, it had nothing to do with my calls to execute Selecter. I found that before releasing them, you must install delgate MKMapView and CLlocationManager. Otherwise, they will continue to work, even if you released the instances, and they have the potential to crash your application.

Thanks for your help Noah!

+4
source share

I had a similar problem when I did not know that I was planning several calls to performSelector on different objects, so the "I" is different in each case.

I would recommend dropping into NSLog (@ "Self:% @", self); before each of your bits of code, for example:

 - (void) viewDidLoad { NSLog(@"Self: %@",self); before [self performSelector:@selector(myStopUpdatingLocation) withObject:nil afterDelay:6]; } - (void) viewWillDisappear:(BOOL)animated { NSLog(@"Self: %@",self); before [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(myStopUpdatingLocation) object:nil]; } 

This will allow you to compare SELF instances to ensure that you execute and release selectors on the same object.

+2
source share

All Articles