我有一个NSArray,在数组中每个项目都有一个名为“venue”的内部数组,然后在另一个名为“location”的数组中。我想按每个“位置”数组中的“距离”值对数组进行排序。
有人能指出我正确的方向,这就是数组。
{
venue = {
beenHere = {
count = 0;
marked = 0;
};
location = {
address = "845 Market St.";
city = "San Francisco";
country = "United States";
crossStreet = "Westfield Food Emporium";
distance = 137;
lat = "37.78459765160777";
lng = "-122.40650538423186";
postalCode = 94103;
state = CA;
};
};
},{
venue = {
beenHere = {
count = 0;
marked = 0;
};
location = {
address = "845 Market St.";
city = "San Francisco";
country = "United States";
crossStreet = "Westfield Food Emporium";
distance = 137;
lat = "37.78459765160777";
lng = "-122.40650538423186";
postalCode = 94103;
state = CA;
};
};
},
在我使用以下内容时,它似乎没有任何效果。
NSSortDescriptor* sortOrder = [NSSortDescriptor sortDescriptorWithKey:@"distance" ascending: YES];
self.venueObject = [venueObject sortedArrayUsingDescriptors: [NSArray arrayWithObject: sortOrder]];
由于
奥利弗
答案 0 :(得分:4)
如果我正确理解你的问题,你就会有一系列词典,并希望在这些词典子键中购买一些值。
您需要使用sortedArrayUsingComparator
:方法。
这样的事情对你有用:
NSArray * sortedVenues = [venues sortedArrayUsingComparator:^NSComparisonResult(NSDictionary * venue1, NSDictionary * venue2) {
float distance1 = [[venue1 valueForKeyPath: @"location.distance"] floatValue];
float distance2 = [[venue2 valueForKeyPath: @"location.distance"] floatValue];
if (distance1 > distance2) {
return NSOrderedDescending;
} else if (distance1 < distance2) {
return NSOrderedAscending;
} else {
return NSOrderedSame;
}
}];