开发者

ObjectiveResource and broken NSNumberFormatter

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 doubleVa开发者_如何学运维lue]]]);

[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.


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


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]];
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜