I want to format a NSDecimalNumber as a Dollars value ($1.50) but Im getting a crash.
This is my method:
+(NSString*) formatPriceForUser:(NSDecimalNumber*)dPrice{
NSNumberFormatter *formatter;
if (!formatter) {
formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterCurrencyStyle];
[formatter setMaximumIntegerDigits:6];
[formatter setMaximumFractionDigits:2];
}
NSString* str = [formatter stringFromNumber:dPrice];
return str;
}
The crash happens on the stringFromNumber invocation.
What am I doing wrong?
Thanks in advance.
Gonso
You’re not initializing the local variable
formatter, so it’s getting initialized with whatever garbage is left on the stack, and the initialif (!formatter)test is failing. In C/C++/Objective-C, stack variables are NOT automatically initialized to zero. The fix is to explicitly initializeformattertonil:Also note that by declaring it as
static, it will persist across function calls, so you avoid reinitializing it for every call.