2012-04-24 120 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