2012-04-24 66 views
1

我有一個自定義的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距離關鍵

回答

1

通過從一些這方面的幫助。論壇和我的朋友們,我能夠將這個解決方案拼湊在一起

答案是在加載表視圖之前使用for循環併爲方法中的每個位置創建字典然後我使用NSSortDescriptor來完成排序,它每工作fectly。

請參閱下面的代碼以獲取最終解決方案。

-(void)getData:(NSData *) data 
{ 

NSError *error; 

// load the jsonArray with the JSON Data 
jsonArray = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error]; 


//define the unsorted dealers array 
unsortedDealers = [[NSMutableArray alloc] initWithCapacity:1000]; 

// start at row 0 
int index = 0; 

// loop through each dealer and calculate distance from current location 
for (NSDictionary *dealer in jsonArray) 
{ 
    //create dictionary from JSON Array 
    infoDict = [jsonArray objectAtIndex:index]; 

    //get the coordidates from current location 
    CLLocation *currentlocation = [[CLLocation alloc] initWithLatitude:locationManager.location.coordinate.latitude longitude:locationManager.location.coordinate.longitude]; 

    //get the coordinates for dealer at row 
    // dlr lat and longs are switched in the database 
    CLLocation *locationforindex = [[CLLocation alloc] initWithLatitude:[[infoDict objectForKey:@"dlrlong"]doubleValue] longitude:[[infoDict objectForKey:@"dlrlat"]doubleValue]]; 

    //calculate the distance from current location to dealer at row and format it in miles 
    CLLocationDistance dist = ([locationforindex distanceFromLocation:currentlocation]*0.0006213711922); 

    //define the distance for display 
    NSNumber *distanceForDict = [NSNumber numberWithDouble:dist]; 

    //define the distance for sorting 
    NSString *distanceForSort = [NSString stringWithFormat:@"%.1f",dist]; 

    //create a dictionary for each dealer and define the values for each key 
    NSMutableDictionary *dealerDict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:[infoDict objectForKey:@"dlrname"] , @"dlrname", [infoDict objectForKey:@"dlrcity"], @"dlrcity", [infoDict objectForKey:@"dlrstate"] , @"dlrstate", [infoDict objectForKey:@"dlrzip"], @"dlrzip", [infoDict objectForKey:@"dlradd"] , @"dlradd", distanceForDict , @"dlrdistance" , distanceForSort , @"dlrsortdistance" , [infoDict objectForKey:@"dlremail"] , @"dlremail" , [infoDict objectForKey:@"dlrfax"] , @"dlrfax" , [infoDict objectForKey:@"dlrhours"] , @"dlrhours" , [infoDict objectForKey:@"dlrlat"], @"dlrlat",[infoDict objectForKey:@"dlrlong"] , @"dlrlong" , [infoDict objectForKey:@"dlrnum"], @"dlrnum",[infoDict objectForKey:@"dlrphone"] , @"dlrphone" , [infoDict objectForKey:@"dlrwebsite"], @"dlrwebsite", nil]; 

    //add dictionary to the unsorted array 
    [unsortedDealers addObject:dealerDict]; 

    // iterate through the list of dealers 
    ++index; 

} 

// creates the sorting element 
NSSortDescriptor *sortDescriptor; 

//define what you want to sort by 
sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"dlrdistance" ascending:YES]; 

// build new array with thosed elements to be sorted 
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor]; 

// create new array based on the sorted value 
sortedDealers = [unsortedDealers sortedArrayUsingDescriptors:sortDescriptors]; 

[self.tableView reloadData]; 

//error message if there is no data found. Usually this is an error with the connection, 
//it should never return empty 
if (jsonArray == nil) 
{ 
    NSLog(@"No Data Loaded. Please check your internet connection"); 
} 

}

0

如果你這樣做:?

NSDictionary *aDict = [NSDictionary dictionaryWithDictionary:info]; 
NSArray *anArray = [aDict allValues]; 

它會返回,然後可以排序使用NSSortDescriptor數組

+0

它拋出一個valueForUndefinedKey當我嘗試使用「距離」在NSSortDescriptor – 2012-04-24 23:27:45

+0

很抱歉,但貴陣列包含什麼樣的對象?如果我沒有弄錯,它應該是一個字典數組,以便排序描述符在數組中的每個對象上都有鍵進行比較。我對此有點新,但我認爲這是發生了什麼。 – geraldWilliam 2012-04-25 00:01:56

+0

它從一個JSON序列化開始,到一個名爲_info_的NSDictionary。它具有諸如位置名稱,地址等的值以及諸如_dlrname_,_dlrcity_等的關鍵字,因爲我已經計算出如何將_distanceFromLocation_插入到具有對應關鍵字的值中。使用NSLog,我已經驗證了距離(NSNumber)存儲在鍵_distance_中。我遇到的問題是如何使用NSSortDescriptor對基於距離的UITableView進行排序 – 2012-04-25 21:02:16