iPhone NSNumberFormatter setFormat:

Dan Morgan picture Dan Morgan · Jan 6, 2009 · Viewed 12.3k times · Source

It appears as though NSNumberFormatter's method for setting custom formatters. setFormat: isn't available on the iPhone...

SO this... crashes my app:

NSNumberFormatter *lengthFormatter = [[NSNumberFormatter alloc] init];
[lengthFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
[lengthFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
[lengthFormatter setFormat:@"#,##0.0M"];

Has this occurred to anyone else?

Thanks,

Dan **ANSWERED BELOW. NSNumberFormatter also has methods called setPositiveFormat: setNegativeFormat: which replace the depreciated setFormat: **

Answer

Jason Coco picture Jason Coco · Jan 6, 2009

Yes, it's documented as a note in the NSNumberFormatter Class Reference (requires login). The note says:

iPhone OS Note: iPhone OS supports only the modern 10.4+ behavior. 10.0-style methods and format strings are not available on iPhone OS.

EDIT: Added more text to support follow-up questions.

You could re-write yours to something similar:

NSNumberFormatter *lengthFormatter = [[NSNumberFormatter alloc] init];
[lengthFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
[lengthFormatter setPositiveSuffix:@"M"];
[lengthFormatter setNegativeSuffix:@"M"]; // assuming it can go negative

I suggest taking a look at the document that I linked above. It's specifically for the iPhone version of NSNumberFormatter, so none of the methods that will cause your application to crash are in there. It's also designed to take far more advantage of the user's localized settings than the original NSNumberFormatter did. There are groups of methods for restricting what shows up and such while still taking advantage of the user's preferences. Unfortunately, there is no longer a setFormat: method.