我使用以下代码使用CLLocation检索距离列表:
ViewController.h
@property (nonatomic) CLLocationDistance kilometers;
@property (nonatomic) CLLocation *startLocation;
@property (nonatomic) CLLocation *endLocation;
@property (nonatomic) NSMutableDictionary *allDistances;
ViewController.m
self.startLocation = [[CLLocation alloc] initWithLatitude:aPlacemark.location.coordinate.latitude longitude:aPlacemark.location.coordinate.longitude] ;
self.endLocation = [[CLLocation alloc] initWithLatitude:placemark.location.coordinate.latitude longitude:placemark.location.coordinate.latitude] ;
self.kilometers = [self.startLocation distanceFromLocation:self.endLocation] / 1000;
就是说,我想显示在UITableView中返回的距离列表。是否可以将返回的CLLocation距离添加到NSMutableDictionary(我的NSMutableDictionary名为allDistances)中?
当前,如果我尝试在像这样的单元格中显示self.kilometers的值,则每次都会得到相同的值:
[[cell kmAway] setText:[NSString stringWithFormat:@"%f", self.kilometers]];
最佳答案
您对每个用户的距离计算似乎已被覆盖。
我假设allDistances
由userID
键(或类似的键)。在这种假设下,距离计算完成后,您需要将该距离插入allDistances
中,如下所示:
CLLocationDistance distanceInKilometers = [self.startLocation distanceFromLocation:self.endLocation] / 1000.0;
self.allDistances[userID] = @(distanceInKilometers);
注意:
@()
是必需的,以便在Objective-C集合(例如double
)中存储原始类型(即CLLocationDistance
,即NSMutableDictionary
)。这称为“装箱”,它将CLLocationDistance
变成NSNumber *
。现在,所有距离都已计算并存储在
allDistances
中,在-tableView:cellForRowAtIndexPath:
方法中,可以将其用于每个单元格:// Assuming you know what user this cell belongs to,
// pull the distance out of `allDistances` using their `userID`.
NSNumber *distanceNumber = self.allDistances[userID];
// "Unbox" the number as a `CLLocationDistance`
CLLocationDistance distance = distanceNumber.doubleValue;
// Use that distance to set the cell text
cell.kmAway.text = [NSString stringWithFormat:@"%f", distance];
关于ios - 对象-C-将CLLocation值添加到nsdictionary吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55563439/