NSNumberFormatter正在返回垃圾数据。感兴趣的变量底部是 milesString 。它是四舍五入而不是1.6388。我输入了调试器信息,还添加了testString和num2的调试代码。作为参考,DistanceFormatter是静态的,除了这个函数以外的任何地方都没有修改。我已经尝试用本地实例替换它以查看静态对象是否导致了问题(事实并非如此)。另一个注意事项,当我没有使用roudingMode时,我收到了这个错误。
-(NSString *)distanceStringFromLocation:(CLLocation *)location {
if (!DistanceFormatter) {
DistanceFormatter = [NSNumberFormatter alloc];
[DistanceFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
DistanceFormatter.roundingMode = NSNumberFormatterRoundCeiling;
DistanceFormatter.minimumFractionDigits = 0;
DistanceFormatter.maximumFractionDigits = 4;
}
CLLocationDistance distance = [_location distanceFromLocation:location];
distance = distance / 1000;
NSLocale *locale = [NSLocale currentLocale];
BOOL isMetric = [[locale objectForKey:NSLocaleUsesMetricSystem] boolValue];
if (isMetric) {
return [NSString stringWithFormat:@"%@ kilometers away", [DistanceFormatter stringFromNumber:[NSNumber numberWithFloat:distance]]];
} else {
CGFloat miles = 0.621371 * distance; //miles = (CGFloat) 1.63877738
NSNumber *num = [NSNumber numberWithFloat:miles]; //num = (__NSCFNumber *)(float)1.63878
NSString *testString = [NSString stringWithFormat:@"%f", miles]; //testString = (__NSCFString *) @"1.63877"
NSNumber *num2 = [DistanceFormatter numberFromString:testString]; //num2 = (NSNumber *)nil
NSString *milesString = [DistanceFormatter stringFromNumber:num]; //milesString = (__NSCFString *)@"2"
return [NSString stringWithFormat:@"%@ miles away", milesString];
}
}
答案 0 :(得分:0)
您已分配但未初始化日期格式化程序。
DistanceFormatter = [NSNumberFormatter alloc];
应该是
DistanceFormatter = [[NSNumberFormatter alloc] init];
通过该更改,您可以获得结果milesString = @"1.6388"
。