1

我有一个 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]];

谢谢

奥利弗

4

1 回答 1

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;
    }
}];
于 2012-04-19T11:14:54.613 回答