Good articles to my personal technology blog: https://cainluo.github.io/14975320210226.html
Unit conversion
Unit conversion in fact, in iOS development, has always been a problem, although conversion is not necessarily encountered in most apps, but in some professional apps, such as navigation, measurement, calculation, car assistance and other apps, it is painful, because the official does not provide such API, basically write their own, Or integrate third-party libraries.
In an effort to improve the API again, Apple’s dad added a library called Measurement to the Foundation to take care of unit conversion.
The project here is in the Objective-C version, if you like the Swift version, you can check it out here.
Create a project
Since this is pretty simple, I won’t overcomplicate it and look directly at the code:
// Initializes a cardinality of seconds
NSMeasurement *seconds = [[NSMeasurement alloc] initWithDoubleValue:Awesome!
unit:NSUnitDuration.seconds];
// Convert to minutes
NSMeasurement *minutes = [seconds measurementByConvertingToUnit:NSUnitDuration.minutes];
// Convert to hours
NSMeasurement *hours = [seconds measurementByConvertingToUnit:NSUnitDuration.hours];
NSString *secondsString = [NSString stringWithFormat:"@" % 2 f seconds, seconds.doubleValue];
NSString *minutesString = [NSString stringWithFormat:Minutes "@" % 2 f, minutes.doubleValue];
NSString *hoursString = [NSString stringWithFormat:"@" % 2 f hours, hours.doubleValue];
Copy the code
I won’t post the UI code, you can go to the project to see for yourself, the overall effect is like this:
Types of conversion units supported
- NSDimension dimension
- NSUnitAcceleration per second per square meter
- NSUnitAngle Angle
- NSUnitArea square meters
- NSUnitConcentrationMass per g/l
- NSUnitDispersion: per million
- NSUnitDuration seconds
- NSUnitElectricCharge coulomb
- NSUnitElectricCurrent ampere
- NSUnitElectricPotentialDifference v
- NSUnitElectricResistance ohm
- NSUnitEnergy joule
- NSUnitFrequency Hertz
- NSUnitFuelEfficiency l / 100km
- NSUnitLength m
- NSUnitIlluminance kg
- NSUnitPower Watts, USA
- NSUnitPressure Newton per square meter
- NSUnitSpeed s/m
- NSUnitTemperature kelvin
- NSUnitVolume l
conclusion
There are more than 170 different unit conversions available in this library, but I’ve only used a few here. There are more methods to explore, and if you want to learn more, you can check out WWDC 2016.
The project address
The address of the project: https://github.com/CainRun/iOS-10-Characteristic/tree/master/7.Measurement