I have a custom UITableView populated by JSON data brought into a NSMutableDictionary. I then create a mutablecopy so that I can add the value of the distanceFromLocation method to the dictionary. What I am trying to do is to then sort the the cells by the closest distance using that new object. I have looked at other examples of using NSSortDescriptor, but that is talking about sorting arrays. How can I either sort the cells from the dictionary or create an array from the dictionary to use the 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];
EDIT: Assigned distance to object to call later in 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];
However it throws valueForUndefinedKey for the key distance. How do I define the distance key in “initWithKey?
Through some help from this forum and my friends, I was able to piece this solution together.
The answer was to use a for loop and create dictionaries for each location in a method before it loads the table view. Then I used a NSSortDescriptor to do the sorting, and it worked perfectly.
See the code below for the final solution.
}