我有一个自定义 UITableView,由带入 NSMutableDictionary 的 JSON 数据填充。然后我创建一个 mutablecopy,以便我可以将 distanceFromLocation 方法的值添加到字典中。我要做的是然后使用该新对象按最近距离对单元格进行排序。我看过其他使用 NSSortDescriptor 的例子,但那是在谈论排序数组。如何对字典中的单元格进行排序或从字典中创建一个数组以使用 NSSortDescriptor?
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"dealerlistcell";
DealerListCell *cell = (DealerListCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[DealerListCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
//gets JSON data and loads into Dictionary
NSMutableDictionary *info = [json objectAtIndex:indexPath.row];
NSMutableDictionary *infocopy = [info mutableCopy];
//pulls the current user location
CLLocation *currentlocation2 = [[CLLocation alloc] initWithLatitude:locationManager.location.coordinate.latitude longitude:locationManager.location.coordinate.longitude];
//gets the latitude and longitude from info dictionary to calculate distancefromlocation for each cell
CLLocation *locationforindex = [[CLLocation alloc] initWithLatitude:[[info objectForKey:@"dlrlat"]doubleValue] longitude:[[info objectForKey:@"dlrlong"]doubleValue]];
//calculates the distance
CLLocationDistance dist = ([locationforindex distanceFromLocation:currentlocation2]*0.0006213711922);
//format the distance to a string for the label
NSString *distancestring = [NSString stringWithFormat:@"%.1f miles",dist];
//create object with distance to add to dictionary
NSNumber *distance = [NSNumber numberWithDouble:dist];
编辑:分配到对象的距离,以便稍后在 NSSortDescriptor 中调用
//add to dictionary
[infocopy setObject:distance forKey:@"distance"];
//create array from dictionary
NSDictionary *aDict = [NSDictionary dictionaryWithDictionary:infocopy];
NSArray *anArray = [aDict allValues];
//implemented NSSortDescriptor
NSSortDescriptor *sorter [[NSSortDescriptor alloc] initWithKey:@"distance" ascending: YES];
NSArray *sortdescriptors = [NSArray arrayWithObject:sorter];
[anArray sortedArrayUsingDescriptors:sortdescriptors];
但是,它会为键距离抛出 valueForUndefinedKey。如何在“initWithKey”中定义距离键?