我有一個自定義的UITableView填充到NSMutableDictionary中的JSON數據。然後我創建一個mutablecopy,以便我可以將distanceFromLocation方法的值添加到字典中。我試圖做的是,然後使用該新對象按最近距離對單元格進行排序。我已經看過使用NSSortDescriptor的其他例子,但那是在討論排序數組。我怎樣才能從字典中排序單元格或從字典中創建一個數組來使用NSSortDescriptor?排序基於NSDictionary的UITableView的密鑰
- (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距離關鍵
它拋出一個valueForUndefinedKey當我嘗試使用「距離」在NSSortDescriptor – 2012-04-24 23:27:45
很抱歉,但貴陣列包含什麼樣的對象?如果我沒有弄錯,它應該是一個字典數組,以便排序描述符在數組中的每個對象上都有鍵進行比較。我對此有點新,但我認爲這是發生了什麼。 – geraldWilliam 2012-04-25 00:01:56
它從一個JSON序列化開始,到一個名爲_info_的NSDictionary。它具有諸如位置名稱,地址等的值以及諸如_dlrname_,_dlrcity_等的關鍵字,因爲我已經計算出如何將_distanceFromLocation_插入到具有對應關鍵字的值中。使用NSLog,我已經驗證了距離(NSNumber)存儲在鍵_distance_中。我遇到的問題是如何使用NSSortDescriptor對基於距離的UITableView進行排序 – 2012-04-25 21:02:16