在我的项目中,我尝试使用块 sortedArrayUsingComparator:^(id a, id b) 将已知位置与输入位置进行比较。我有一个名为 locationArray 的字典数组,其中包含一个纬度和一个与该经度点相对应的站号。我尝试将每个 locationArray 站与输入的站进行比较。我通过取两者之间差异的绝对值来做到这一点,这给了我一个距离。然后我尝试根据输入站点的距离从最近到最远对 locationArray 进行排序。
//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]);
该块运行,但它没有按预期对位置数组进行排序。orderedPlaces 返回一个未排序的位置数组。通过在块组件上运行 NSLOG,我看到它成功识别了位置数组并创建了距离对象。我一定遗漏了一些东西,因为我在项目的不同部分使用了相同的代码,我将位置数组与用户位置的纬度进行了比较,并且效果很好。请帮助我确定使其无法按预期工作的问题。
*如果您需要更多信息或说明,请询问。