简体   繁体   English

使用自定义对象对NSArray进行排序

[英]Sort NSArray with custom objects

In my Xcode project I have the following classes: 在我的Xcode项目中,我有以下类:

Address 地址

@interface LDAddress : NSObject{
    NSString *street;
    NSString *zip;
    NSString *city;
    float latitude;
    float longitude;
}

@property (nonatomic, retain) NSString *street;
@property (nonatomic, retain) NSString *zip;
@property (nonatomic, retain) NSString *city;
@property (readwrite, assign, nonatomic) float latitude;
@property (readwrite, assign, nonatomic) float longitude;

@end

Location 地点

@interface LDLocation : NSObject{
    int locationId;
    NSString *name;
    LDAddress *address;
}
@property (readwrite, assign, nonatomic) int locationId;
@property (nonatomic, retain) LDAddress *address;
@property (nonatomic, retain) NSString *name;

@end

In an subclass of UITableViewController, there is a NSArray containing a lot of unsorted objects of LDLocations. 在UITableViewController的子类中,有一个NSArray包含许多LDLocations的未排序对象。 Now, I want to sort the NSArray's objects ascending based on the property city of a LDAddress. 现在,我想根据LDAddress的属性城市对NSArray的对象进行升序排序。

How can I sort the array using NSSortDescriptor? 如何使用NSSortDescriptor对数组进行排序? I tried the following, but the app dumps when sorting the array. 我尝试了以下方法,但在排序数组时应用程序转储。

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"Address.city" ascending:YES];
[_locations sortedArrayUsingDescriptors:@[sortDescriptor]];

尝试将第一个键设为小写。

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"address.city" ascending:YES];

You can also sort an array with blocks: 您还可以使用块对数组进行排序:

    NSArray *sortedLocations = [_locations sortedArrayUsingComparator: ^(LDAddress *a1, LDAddress *a2) {
        return [a1.city compare:a2.city];
    }];

This will allow to sort with multiple types. 这将允许使用多种类型进行排序。 Like we need to sort the Movie based on time and if the time is equal then need to sort by name. 就像我们需要根据时间对电影进行排序,如果时间相等,则需要按名称排序。

NSArray *sortedArray = [childrenArray sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
        NSNumber *first = [NSNumber numberWithLong:[(Movie*)a timeInMillis]];
        NSNumber *second = [NSNumber numberWithLong:[(Movie*)b timeInMillis]];
        NSComparisonResult result =  [first compare:second];
        if(result == NSOrderedSame){
            result = [((NSString*)[(Movie*)a name] ) compare:((NSString*)[(Movie*)b name])];
        }
        return  result;
    }];
-(NSArray*)sortedWidgetList:(NSArray*)widgetList
{
    NSSortDescriptor *firstDescriptor = [[NSSortDescriptor alloc] initWithKey:@"itemNum" ascending:YES];

    NSArray *sortDescriptors = [NSArray arrayWithObjects:firstDescriptor, nil];

    NSArray *sortedArray = [widgetList sortedArrayUsingDescriptors:sortDescriptors];

    return sortedArray;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM