views:

36

answers:

2

I have an application that uses ObjectiveResource and has a class that contains NSNumber properties. I am trying to format the NSNumber values as integers, and have the following code:

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];

[formatter setNumberStyle:NSNumberFormatterCurrencyStyle];

NSLog(@"Price: %@", [formatter stringFromNumber:self.item.price])
NSLog(@"Price: %@", [formatter stringFromNumber:[NSNumber numberWithDouble:[self.item.price doubleValue]]]);

[formatter release];

Which outputs:

2010-07-15 19:33:45.371 Sample[4193:207] alcohol: (null)
2010-07-15 19:33:45.453 Sample[4193:207] alcohol: $13.50

I'm not sure why the first item is outputting (null), yet the second works fine. I'd prefer to use the syntax from the first, and not have to re-create a NSNumber.

+2  A: 

self.item.price is probably an NSString?

Through an awful hack I can reproduce your result exactly:

NSNumber *price = (NSNumber*)@"13.5"; // *shiver*, don't try this at home!
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];

[formatter setNumberStyle:NSNumberFormatterCurrencyStyle];

NSLog(@"Price: %@", [formatter stringFromNumber:price]);
NSLog(@"Price: %@", [formatter stringFromNumber:[NSNumber numberWithDouble:[price doubleValue]]]);

Since NSString responds to doubleValue, this comes out:

2010-07-16 17:17:50.384 test[716:207] Price: (null)
2010-07-16 17:17:50.386 test[716:207] Price: $13.50
mvds
I am not sure if it solves, but it is a smart way
vodkhang
Thanks MVDS. That I took a look through the ActiveResource code and this is indeed the case. I added the fix below:
Kevin Sylvestre
+1  A: 

To fix, in the XML Element Delegate (XMLElementDelegate.m) a section of code needed to be uncommented to support NSNumber. The line is:

// uncomment this if you what to support NSNumber and NSDecimalNumber
// if you do your classId must be a NSNumber since rails will pass it as such
else if ([type isEqualToString:@"decimal"]) {
    return [NSDecimalNumber decimalNumberWithString:propertyValue];
}
else if ([type isEqualToString:@"integer"]) {
    return [NSNumber numberWithInt:[propertyValue intValue]];
}
Kevin Sylvestre