How to solve this performSelector:withObject:afterDelay: problem?
I have a view controller, which calls performSe开发者_Go百科lector:withObject:afterDelay. However, if I remove that view controller right after calling this, my app crashes as soon as the system tries to perform the delayed selector on that (deleted) view controller.
Now how can I go about this? I need to get rid of the view controller to save memory, so there's no way to let it hang around.
Any way to cancel a delayed perform selector before it performs?
I suggest to use an NSTimer
instead. You can simply invalidate
the timer to make sure it will never be called after the UIViewController
has gone away. A good moment to invalidate
the timer is for example in viewWillDisappear:
.
This does mean that the timer is owned by the view controller. But that is a good design anyway.
You can't perform a selector on a deleted object, you either need to have the object around, or do the work with some other smaller object that you can have hanging around.
To cancel there is a cancelPreviousPerformRequestsWithTarget:selector:object: or cancelPreviousPerformRequestsWithTarget: method.
精彩评论