views:

5627

answers:

4

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: **

+2  A: 

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.

Jason Coco
A: 

ThankYou. Do you know how easily to add a symbol, such as a 'M' onto the end of a number using a NSNumberFormatter? Surely the new 10.4 behaviour has an equivalent to setFormat: right?

Dan Morgan
I updated my answer a bit based on this follow-up. In the future, you should make these follow-up questions as either comments to other people's answers or as an edit to your own question :) Otherwise people will start down-voting you and telling you that SO is not a forum...
Jason Coco
A: 

Thanks so much Jason! Your are a true cocoa genius! If anyone wants to know a way of solving my problem without using setFormat: then check Jason's comment on my follow up comment.

Dan Morgan
A: 

Hi All

Im also getting a crash on the iPhone with this code:

+(NSString*) formatPriceForUser:(NSDecimalNumber*)dPrice{ NSNumberFormatter *formatter;

if (!formatter) { 
 formatter = [NSNumberFormatter alloc]; 
 [formatter init];
 [formatter setNumberStyle:NSNumberFormatterCurrencyStyle];
} 
NSString* str = [formatter stringFromNumber:dPrice];
return str;

}

Any idea of what Im doing wrong?

Thanks in advance Gonso

stringFromNumber accepts NSNumber, instead of NSDecimalNumber. Also, is your dPrice really a valid number? tru using NSLog to debug.
Shivan Raptor