UIDatePicker Memory Leak with ARC

2.1k Views Asked by At

I'm making an app that has a few view controllers with UIDatePicker controls.

After having lots of memory warnings, I've done a lot of debugging on the cause. Using instruments, I was able to see that whenever a view controller containing a UIDatePicker appeared, memory usage was going up by 2-3mb. Ultimately, this leads to a memory warning. While I can do so much in here, and have seen a dramatic decrease in crashes since re-writing these functions, I'm still not comfortable with this behaviour and want to fix it.

The UIDatePicker's are part of the XIB file. I've tried taking them out of the XIB and programmatically adding them. This doesn't solve the problem. I've also tried using a (thread-safe" singleton. This limits memory usage to only one instance (so memory usage doesn't increase), but I'm trying to avoid singletons wherever possible. Should I just suck it up and use a singleton?

I'm seeing this behaviour on iOS 5 and 4.3, across all devices that run it. I'm using ARC, as the title suggests.

Instruments does not show any memory leaks.

Here is a screenshot from Instruments. Each step up in usage is when a VC containing a date picker appears. The baseline at the start of the graph is 2.3mb of memory usage.

https://i.stack.imgur.com/1S7ns.png

Cheers!

2

There are 2 best solutions below

0
On

I seem to have solved my own question. As this was an inputView, and I also had a UIToolbar with a "Done" button as the inputAccessoryView.

So now I create these programatically in viewWillAppear. In viewWillDisappear, I set the UITextField's inputView and inputAccessoryView to nil, and the date picker and date picker toolbar to nil.

They are no longer in the XIB file.This seems to work really well - memory spikes up by 3mb, then goes back down the second the views disappear. Now the app is running consistently at under 10mb of live memory - it spikes up to 15mb on occasion but very rarely.

Thanks for the help sudo rm -rf and Rob - heapshot analysis helped to try and get to the bottom of it.

1
On

The tool you want to use here is called heapshot. It will help you narrow down the types of objects that are being incorrectly held onto. As @sudo notes, the problem is probably in your delegate rather than the date picker itself. You're probably not "leaking" in the strictest sense of the term. You're probably just holding onto memory that you didn't mean to (which looks a lot like a leak).

You should take a careful look at whether you have any circular strong references. Do you have objects that have a strong reference to their delegate for instance? That will typically lead to a retain loop (which will never be released under ARC). Heapshot can help you find these objects.