【发布时间】:2012-02-16 08:45:16
【问题描述】:
我一直在开发一个 iPhone 应用程序,其中我有一个 NSMutableArray 中的用户列表,如下所示。
myMutableArray: (
{
FirstName = Getsy;
LastName = marie;
Latitude = "30.237314";
Longitude = "-92.461008";
},
{
FirstName = Angel;
LastName = openza;
Latitude = "30.260329";
Longitude = "-92.450414";
},
{
FirstName = Sara;
LastName = Hetzel;
Latitude = "30.2584499";
Longitude = "-92.4135357";
}
)
我需要通过计算纬度和经度,根据我所在位置附近的位置对用户进行排序。直到现在我都无法做到这一点。有人可以帮我提供一些样品吗?
更新:按照 Mr.sch 的建议,我正在尝试如下所示。请检查我更新的代码。还好吗?
NSArray *orderedUsers = [myMutableArray sortedArrayUsingComparator:^(id a,id b) {
NSArray *userA = (NSArray *)a;
NSArray *userB = (NSArray *)b;
CGFloat aLatitude = [[userA valueForKey:@"Latitude"] floatValue];
CGFloat aLongitude = [[userA valueForKey:@"Longitude"] floatValue];
CLLocation *participantALocation = [[CLLocation alloc] initWithLatitude:aLatitude longitude:aLongitude];
CGFloat bLatitude = [[userA valueForKey:@"Latitude"] floatValue];
CGFloat bLongitude = [[userA valueForKey:@"Longitude"] floatValue];
CLLocation *participantBLocation = [[CLLocation alloc] initWithLatitude:bLatitude longitude:bLongitude];
CLLocation *myLocation = [[CLLocation alloc] initWithLatitude:locationCoordinates.latitude longitude:locationCoordinates.longitude];
CLLocationDistance distanceA = [participantALocation distanceFromLocation:myLocation];
CLLocationDistance distanceB = [participantBLocation distanceFromLocation:myLocation];
if (distanceA < distanceB) {
return NSOrderedAscending;
} else if (distanceA > distanceB) {
return NSOrderedDescending;
} else {
return NSOrderedSame;
}
}];
谢谢!
【问题讨论】:
-
嘿,Getsy,请参阅下面的我的答案..
-
您能否验证 myMutableArray 是否为 nil,或者在您添加的代码的第一行之前是否为空。
-
你太棒了!非常感谢!
-
不,bLatitude 和 bLongitude 需要使用 userB。