Sorry if this is a noob question, but I get tripped up on some simple things as I’m starting to learn to program. If I use a NSDateFormatter in one of my ViewControllers to display the date I want in a certain format, and the format doesn’t change, is it “best practices” to declare that NSDateFormatter as an ivar of my class or property of my class and initialize it in the viewDidLoad so I can reuse it in my different methods? Right now I just instantiate one whenever I need it in a method that deals with the display and was wondering if it’s better to just keep declaring it, or declare it once and just use it throughout the viewController class. thanks!
Share
It’s not a “noob question”; it’s a reasonable question with a reasonable answer.
From a pure efficiency standpoint, you’re optimizing prematurely. Don’t worry, be happy. If you’re managing memory correctly (so that you’re not leaking NSDateFormatters) it really shouldn’t matter how you obtain a particular instance, especially given that this is such a lightweight object. If you’re creating a new NSDateFormatter 1000 times in a loop, you’re being silly, but if you’re creating the object now and then when you need it and it’s going back out of existence properly, it’s no big deal.
On the other hand, from an architectural standpoint, make sure what you are doing is DRY. If the date formatter needs any configuration at all, don’t repeat yourself each time you create it; write a method that supplies the date formatter the same way each time so that the configuration code is all in just one place.