2012-04-24 6 views
1

NSMutableDictionary에 가져온 JSON 데이터로 채워진 사용자 지정 UITableView가 있습니다. 그런 다음 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]; 

편집 : 할당 된 거리가 키 거리 valueForUndefinedKey을 던져 그러나 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]; 

를 호출하는 객체입니다. 어떻게 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

나는 NSSortDescriptor –

+0

죄송에서 "거리"를 사용하려고 노력하지만, 배열 객체의 어떤 종류를 포함 않을 때 그것은 valueForUndefinedKey을 던져? 내가 잘못 본 것이 아니라면 정렬 사전에 배열의 각 객체에 키가있는 사전 배열을 비교해야합니다. 나는이 일에 익숙하지 만, 그렇게되고 있다고 생각합니다. – geraldWilliam

+0

_info_라는 NSDictionary에 JSON Serialization으로 시작합니다. 위치, 주소 등의 이름과 _dlrname_, _dlrcity_ 등의 키와 같은 값을 가지고 있습니다. 이후 _distanceFromLocation_을 해당 키가있는 값에 삽입하는 방법을 알아 냈습니다. NSLog를 사용하여 _distance_ 키에 거리 (NSNumber)가 저장되어 있는지 확인했습니다. 내가 겪고있는 문제는 NSSortDescriptor를 사용하여 UITableView를 거리에 따라 정렬하는 방법입니다. –