Stunning NSString formatting behavior

Today I ran into a rather strange problem. I have this static method (part of the source CommonUtilities file that I just created that collects all the small common methods that I would like to get anywhere in my code, for example, I usually do btw ...)

I just want to convert a number to its scientific value using international system notation (k, M, G, etc.)

Here is the code:

+ (NSString*)scientificFormatedStringForValue:(NSNumber*)value andUnits:(NSString*)_units { NSMutableString* retStr = [NSMutableString string]; long long longValue = [value longLongValue]; if (longValue > 1000000000) { [retStr appendFormat:@"%d Md%@", longValue / 1000000000, _units]; } else if (longValue > 1000000) { [retStr appendFormat:@"%d M%@", longValue / 1000000, _units]; } else if (longValue > 1000) { [retStr appendFormat:@"%dk%@", longValue / 1000, _units]; } else { [retStr appendFormat:@"%d %@", longValue, _units]; } return retStr; } 

Is it pretty easy? Ok, here's the deal: _units not being converted properly.

In my example, I use this:

 [CommonUtilities scientificFormatedStringForValue:[NSNumber numberWithLongLong:longValue] andUnits:@"€"]; 

I get (null) as _units for the formatted string. If I print the value of _units , that is the point. So, to try and debug this, I simply replaced:

 [retStr appendFormat:@"%d M%@", longValue / 1000000, _units]; 

with

 [retStr appendFormat:@"%d M%@", longValue / 1000000, @"€"]; 

Still not working. He tried to convey one character (thinking that perhaps he should be converted to some UTF8 stuff or something else. So I changed the invocation method to:

 [CommonUtilities scientificFormatedStringForValue:[NSNumber numberWithLongLong:longValue] andUnits:@"e"]; 

Still shitty stuff. I even changed @ "€" to [NSString stringWithString: @ "€"], but still the same result! I can’t understand what’s wrong here, I’m stuck.

I was thinking about a problem in the encoding of the source file, so I deleted it and recreated, but still the same question ....

If someone has even the smallest key, that would be very helpful. Thanks guys...

+4
source share
1 answer

The problem is that you are trying to write int (32 bits), but you are passing long long (64 bits) and reading the first 4 bytes of your longValue for value and the last 4 bytes for _units . It so happened that the value in the lower bytes of your long long is nil and did not cause a failure. To print a long value, you need to use %lld instead of %d .

  longValue NSString* /---------------\ /---------\ | 8 bytes | | 4 bytes | \---------------/ \---------/ ^^^^^^^^ ^^^^^^^^ ^^^^^^^^^ %d %@ This gets ignored. (reads 4) (reads this 4 bytes which happen to be nil) 
+3
source

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


All Articles