【问题标题】:Adding null values to array in Objective-C在 Objective-C 中向数组添加空值
【发布时间】:2016-01-11 21:05:59
【问题描述】:

在一个快速的项目中,我能够轻松地做到这一点。我有一组 CLLocationCoordinate2D 和 CLLocationDistances

这是 swift 代码(在 PFQuery 中)它工作得很好

if let returnedLocation = object["location"] as? PFGeoPoint
{                   
    let requestLocation = CLLocationCoordinate2DMake(returnedLocation.latitude, returnedLocation.longitude)                       
    self.locations.append(requestLocation)                  
    let requestCLLocation = CLLocation(latitude: requestLocation.latitude, longitude: requestLocation.longitude)
    let driverCLLocation = CLLocation(latitude: location.latitude, longitude: location.longitude)        
    let distance = driverCLLocation.distanceFromLocation(requestCLLocation)
    self.distances.append(distance/1000)
}

当我尝试在 Objective C 中将它们添加到位置和距离数组时出现错误,因为我正在添加一个没有指针的对象。解决这个问题的最佳方法是什么?谢谢

Objective C 代码(它们都是 NSMutableArrays)

if (object[@"driverResponded"] == nil) {
    NSString *username = object[@"username"];
    [self.usernames addObject:username];
    PFGeoPoint *returnedLocation = object[@"location"];
    CLLocationCoordinate2D requestLocation = CLLocationCoordinate2DMake(returnedLocation.latitude, returnedLocation.longitude);
    //FIX!
    [self.locations addObject:requestLocation];
    CLLocation *requestCLLocation = [[CLLocation alloc]initWithLatitude:requestLocation.latitude longitude:requestLocation.longitude];
    CLLocation *driverCLLocation = [[CLLocation alloc]initWithLatitude:location.latitude longitude:location.longitude];
    CLLocationDistance distance = [driverCLLocation distanceFromLocation:requestCLLocation];
    [self.distances addObject:distance/1000];
}

【问题讨论】:

  • 为什么不将requestCLLocation 添加到self.locations 并在需要时从中提取CLLocationCoordinate2D??
  • 标题中指定的问题中没有null

标签: ios objective-c arrays swift null


【解决方案1】:

您可以这样做以将其存储为 CLLocationCoordinate 这样做:

CLLocationCoordinate2D new_coordinate = CLLocationCoordinate2DMake(returnedLocation.latitude, returnedLocation.longitude);
[self.locations addObject:[NSValue valueWithMKCoordinate:new_coordinate]];

像这样把它拉回来:

CLLocationCoordinate2D coordinate = [[self.locations objectAtIndex:0] MKCoordinateValue];

【讨论】:

  • 谢谢!对于距离 [self.distances addObject:[NSNumber numberWithDouble:distance]];似乎也可以。
  • 很高兴它有帮助!确保将答案标记为正确,以免其他人提交新答案!
猜你喜欢
  • 2022-08-18
  • 1970-01-01
  • 2010-09-17
  • 1970-01-01
  • 1970-01-01
  • 2022-11-29
  • 1970-01-01
  • 2020-03-28
  • 2013-11-28
相关资源
最近更新 更多