tags:

views:

121

answers:

1

Hi

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

+4  A: 

You're not initializing the local variable formatter, so it's getting initialized with whatever garbage is left on the stack, and the initial if (!formatter) test is failing. In C/C++/Objective-C, stack variables are NOT automatically initialized to zero. The fix is to explicitly initialize formatter to nil:

static NSNumberFormatter *formatter = nil;

Also note that by declaring it as static, it will persist across function calls, so you avoid reinitializing it for every call.

Adam Rosenfield
static variables *do* get initialized to nil, actually (as of C99). Only local variables don't. The fix is simply to declare it as static, or to use a new formatter every time (which equally relieves the need to initialize it).
Peter Hosey