2012-07-08 37 views
0

我目前正在从一个sql DB'cachedDist'列设置为双精度的信息。然而,当我把它放到我的应用程序中并创建我的数组时,我将它变成了一个字符串,排序显然会关闭,18.15将在2.15之前。我如何解决在我的代码中,所以它会将距离排序为Double而不是String?按双精度值排序而不是字符串值

在Bar对象中。

NSString *cachedDist 
@property(nonatomic,copy) NSString *cachedDist; 

@synthesize cachedDist; 

我while循环在视图控制器。

while (sqlite3_step(sqlStatement)==SQLITE_ROW) { 
      Bar * bar = [[Bar alloc] init]; 
      bar.barName = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,1)]; 
      bar.barAddress = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,2)]; 
      bar.barCity = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 3)]; 
      bar.barState = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 4)]; 
      bar.barZip = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 5)]; 
      bar.barLat = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 8)]; 
      bar.barLong = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 9)]; 

      if (currentLoc == nil) { 
       NSLog(@"current location is nil %@", currentLoc); 
      }else{ 

      CLLocation *barLocation = [[CLLocation alloc] initWithLatitude:[bar.barLat doubleValue] longitude:[bar.barLong doubleValue]]; 
      bar.cachedDist = [NSNumber numberWithDouble:[currentLoc distanceFromLocation: barLocation]/1000]; 

      [thebars addObject:bar]; 

      } 

我的排序

NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"cachedDist" ascending:YES]; 
sortedArray = [thebars sortedArrayUsingDescriptors:[NSArray arrayWithObject:descriptor]]; 

return sortedArray; 

回答

0

的NSString有一个方法doubleValue,使这个很简单:

double cachedDistance = [cachedDistanceString doubleValue]; 

,你可以在自定义的比较使用您的排序,否则使属性NSNumber或双重排序更容易。 (我不知道你是怎么排序?)

编辑:

我重新评估你的代码,现在看起来我们正在从一个双去一个字符串转换为双..我们可以砍掉中间人,可以这么说。

在你@prototype部分中,更改@property:

// @property(nonatomic,copy) NSString *cachedDist; // old way 
@property(nonatomic) double cachedDist; 

然后分配给它这样的:

bar.cachedDistance = [currentLoc distanceFromLocation: barLocation]/1000; 

,并删除其创建的距离串线(实际上是只是一个双)。

另外,如果你想更面向对象,你可以(?应该)使用的NSNumber对象:

@property(nonatomic,copy) NSNumber *cachedDist; 
... 
bar.cachedDistance = [NSNumber numberWithDouble:[currentLoc distanceFromLocation: barLocation]/1000]; 
+0

我可以改变'bar.cachedDist = distanceString:''到双distanceDouble = [distanceString的doubleValue ];'和'bar.cachedDist = distanceDouble;'? – user1454340 2012-07-09 01:29:23

+0

我尝试了这一点,当我尝试分配'bar.cachedDist = distanceDouble;'我得到一个错误'从不兼容的类型双'指定给NSString' – user1454340 2012-07-09 01:35:26

+0

我编辑包括建议完全删除NSString部分,NSNumber或者属性类型为double。 – 2012-07-09 01:43:44