如何在Objective-C中将NSObject除以一个数字?

时间:2018-01-17 07:54:29

标签: objective-c

我有这段代码:

NSObject *distanceInMeters;
distanceInMeters = [[[[[[googleMapsApiResult objectForKey:@"routes"] objectAtIndex:0] objectForKey:@"legs"] objectAtIndex:0] objectForKey:@"distance"] valueForKey:@"value"];
NSLog(@"%@", distanceInMeters); // this outputs 7578
NSDecimalNumber *roundTripInKilometers;
roundTripInKilometers = distanceInMeters / 500; // It says "Invalid operands to binary expression ('NSObject *' and 'int')

我希望得到15.156,但它不能用一个整数划分对象值。我该怎么办才能获得15.156?

2 个答案:

答案 0 :(得分:2)

你不能从NSObject中划分数字,要做同样的事情,你必须从中获取数字并在任何地方使用

 NSNumber *distanceInMeters;
distanceInMeters = [[[[[[googleMapsApiResult objectForKey:@"routes"] objectAtIndex:0] objectForKey:@"legs"] objectAtIndex:0] objectForKey:@"distance"] valueForKey:@"value"];
NSLog(@"%@", distanceInMeters); // this outputs 7578

NSDecimalNumber *roundTripInKilometers = (NSDecimalNumber *)[NSDecimalNumber numberWithDouble:[distanceInMeters doubleValue] / 500.0];

答案 1 :(得分:0)

您的代码中存在许多问题。首先,您需要将从API获得的值转换为double。一种简单的方法是首先将其转换为NSString的实例。然后使用方法doubleValue从字符串中获取双精度。

接下来将该值除以500:

double roundTripInKilometersDouble = distanceInMeters / 500.0;

然后将该结果放入NSDecimalNumber

NSDecimalNumber *roundTripInKilometers = [NSDecimalNumber numberWithDouble: roundTripInKilometersDouble];

(Haven未测试此代码。)