在我的項目中,我嘗試使用block sortedArrayUsingComparator比較已知位置與輸入位置:^(id a,id b)。我有一個名爲locationArray的字典數組,其中包含lat long和與該lat長點相對應的站號。我嘗試將每個位置陣列站與輸入站進行比較。我通過取兩個距離之間的差值的絕對值來做到這一點,這給了我一個距離。然後,我嘗試根據從最近到最遠的輸入站的距離來排序locationArray。使用Block sortedArrayUsingComparator:^(id a,id b)
//locationArray
#define kStation @"station"
#define kLatitude @"latitude"
#define kLongitude @"longitude"
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"499CSV" ofType:@"csv"];
NSString *csvString = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
NSArray *locations = [csvString componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
NSMutableArray *CSVArray = [NSMutableArray array];
NSCharacterSet *whiteSPNewLine = [NSCharacterSet whitespaceAndNewlineCharacterSet];
for (NSString * location in locations)
{
NSArray *components = [location componentsSeparatedByString:@","];
double latitude = [[components[0] stringByTrimmingCharactersInSet:whiteSPNewLine] doubleValue];
double longitude = [[components[1] stringByTrimmingCharactersInSet:whiteSPNewLine] doubleValue];
NSString *station = [components[2] stringByTrimmingCharactersInSet:whiteSPNewLine];
NSDictionary *dict = @{kLatitude: @(latitude),
kLongitude: @(longitude),
kStation: station};
[CSVArray addObject:dict];
}
NSLog(@"The contents of CSVArray = %@",[CSVArray description]);
{
latitude = "41.674364";
longitude = "-81.23700700000001";
station = 40150;
},
{
latitude = "41.67517";
longitude = "-81.235038";
station = 40763;
},
{
latitude = "41.673106";
longitude = "-81.24017499999999";
station = 39175;
}, ...
我的塊代碼直接跟在locationArray之後。
NSArray *orderedPlaces = [CSVArray sortedArrayUsingComparator:^(id a, id b) {
NSDictionary *dictA;
NSDictionary *dictB;
NSString *locA;
NSString *locB;
int distanceA;
int distanceB;
dictA = (NSDictionary *)a;
dictB = (NSDictionary *)b;
NSLog(@"dictA = %@", dictA);
NSLog(@"dictB = %@", dictB);
locA = [dictA objectForKey:kStation];
locB = [dictB objectForKey:kStation];
NSLog(@"locA = %@", locA);
NSLog(@"locB = %@", locB);
distanceA = abs(stationNumber-[locA intValue]);
distanceB = abs(stationNumber-[locB intValue]);
NSLog(@"distanceA = %d", distanceA);
NSLog(@"distanceB = %d", distanceB);
if (distanceA < distanceB) {
return NSOrderedAscending;
} else if (distanceA > distanceB) {
return NSOrderedDescending;
} else {
return NSOrderedSame;
}
}];
NSLog(@"The contents of array = %@",[orderedPlaces description]);
該塊運行,但它不按照預期排序locationsArray。 orderedPlaces返回unsorted locationsArray。通過在塊組件上運行NSLOG,我發現它成功識別了locationsArray並創建了距離對象。我必須缺少一些東西,因爲我在項目的不同部分使用相同的代碼,我將位置陣列與用戶位置的緯度比較,並且效果很好。請幫助我找出使其無法按預期工作的問題。
*如果您需要更多信息或澄清,請詢問。
站號是沿道路設計的精確點,所以站10000例如與站10100相距100英尺。我真正關心的唯一字典對象是站點離輸入站最近的字典對象,我希望字典對象成爲orderedArray中的第一個(objectAtIndex:0)對象。我使用距離值來比較從輸入站點到locationArray中所有站點的距離,因此距離最近的站點最近。絕對值可以確保大的負數不會被誤認爲是最接近的。請與我聯繫在此 – user2621075