NSNumberFormatter does not return nilSymbol by zero. What am I missing?

iOS 4+ when I pass the nil value to my NSNumberFormatter, I want the nil character (NSString *) to be set at the end. It works for the null character, but not for the nil character. I tried many different configuration settings such as behavior, grouping, etc.

fmtr = [[NSNumberFormatter alloc] init]; [fmtr setNumberStyle:NSNumberFormatterDecimalStyle]; [fmtr setFormatterBehavior:NSNumberFormatterBehaviorDefault]; [fmtr setUsesGroupingSeparator:NO]; [fmtr setNilSymbol:@"###"]; [fmtr setZeroSymbol:@"0000"]; NSLog(@"[fmtr nilSymbol]=>>%@<<", [fmtr nilSymbol]); NSLog(@"[fmtr stringFromNumber:nil]=>>%@<< this should be '###", [fmtr stringFromNumber:nil] ); NSLog(@"[fmtr stringFromNumber:0]=>>%@<<", [fmtr stringFromNumber:[NSNumber numberWithInt:0]] ); NSLog(@"[fmtr stringFromNumber:null]=>>%@<<", [fmtr stringFromNumber:NULL] ); NSLog(@"[fmtr numberFromString:nil]=%@", [fmtr numberFromString:nil] ); NSLog(@"[fmtr numberFromString:@\"0\"]=%@", [fmtr numberFromString:@"0"] ); NSLog(@"[fmtr numberFromString:NULL]=%@", [fmtr numberFromString:NULL] ); 

Here is the test result:

[fmtr nilSymbol] = β†’ ### <<

[fmtr stringFromNumber: nil] = β†’ (null) <<it should be "###

[fmtr stringFromNumber: 0] = β†’ 0000 <

[fmtr stringFromNumber: null] = β†’ (null) <<

[fmtr numberFromString: nil] = (null)

[fmtr numberFromString: @ "0"] = 0

[fmtr numberFromString: NULL] = (null)

+6
source share
1 answer

I don’t know exactly why this does not work when using numberFromString, but I tested it myself and it works if you use "stringForObjectValue" instead. (replace all "stringFromNumber" with "stringForObjectValue")

Edit: found answer

In this blog: http://www.nsformatter.com/blog/2010/6/9/nsnumberformatter.html

He says:

  • (NSString *) stringFromNumber: (NSNumber *) number;

This is a convenient method. This method returns nil if the number is nil, otherwise it calls -stringForObjectValue :. Therefore, it behaves like -stringForObjectValue :, except that it never returns -nilSymbol

It seems that the purpose of the method (do not use nilSymbol)

+12
source

Source: https://habr.com/ru/post/886746/


All Articles