views:

189

answers:

3

What is the right code pattern for NSNumberFormatter?

There are many example on the Internet (including this one: http://mac-objective-c.blogspot.com/2009/04/nsnumberformatter-some-examples.html) where the NSNumberFormatter is allocated and initialized each time it is needed.

Yet some other examples in the Apple Documentation (including International Mountains) prefer to use it as a private property. Another example (Locations) use it through a static variable.

How do you use an NSNumberFormatter? What is the most efficient technique?

+1  A: 

NSNumberFormatter is not an excessively complicated object, so unless you're using it frequently in a tight loop, efficiency doesn't really matter.

With that said, I'd tend to default to keeping it around in a static variable, if you're trying to minimize the number of instances you create.

John Calsbeek
A: 

I think the examples are just showing how to create and use the formatters, not necessarily the most efficient way to use them. My rule of thumb is if the code will use them more than once, I keep them around somewhere. This also makes debugging and maintenance easier.

TechZen
Thank you for your answer! Then, would you use them as a static variable or as a property?
charlax
Depends, if there is just a couple, properties are convenient because you can bind to them (in Cocoa but not yet iPhone.) If I have more than three or four, I like to park then in a dictionary. . Of course, this is largely for keeping track of them. As noted by John Calsbeek, formatters are lightweight objects so even if you recreate then each time, you won't take much of a hit. Don't spend a lot of time worrying about it. Premature optimization is the root of all programming evil.
TechZen
A: 

Here is one more example set that may be of help for those new to NSNumberFormatter:

Formatting Numbers – NSNumberFormatter Examples

John