Iulian Onofrei Iulian Onofrei - 1 year ago 107
iOS Question

Invalidating an NSTimer in dealloc

Following this question, and more specifically, this comment:

because retain (aka strong reference) cycles in the common case where the timer's target is also its owner

I am wondering why
isn't a good place to invalidate an

I remember profiling my app without auto-repeating
invalidation and then with invalidation in
, and the memory correctly freed.

working differently in the latest iOS?

Isn't in fact your overridden
called prior to any
deallocation? What is
even used for, then? If not manually deallocating the respective object's properties?

Answer Source

ARC will only release ( and call dealloc ) objects, when there are no strong references pointing to this object ( no one is retaining ).

NSTimer creates strong reference and it will retain target.

This means, dealloc will not be called, because NSTimer still has strong reference to the object. If there is no Dealloc, this means NSTimer will never be invalidated ... leads to memory leak or even crashes.

There is a way to invalidate timer in dealloc or when target becomes nil. Have a look at the answer here http://stackoverflow.com/a/16822471/1824510

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download