使用自定义对象对NSArray进行排序 [英] Sort NSArray with custom objects

查看:106
本文介绍了使用自定义对象对NSArray进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Xcode项目中,我有以下课程:

In my Xcode project I have the following classes:

地址

@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

位置

@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

在UITableViewController的子类中,有一个NSArray包含很多未分类的LDLocations对象。现在,我想根据LDAddress的属性 city 对NSArray的对象进行升序排序。

In an subclass of UITableViewController, there is a NSArray containing a lot of unsorted objects of LDLocations. Now, I want to sort the NSArray's objects ascending based on the property city of a LDAddress.

如何使用NSSortDescriptor对数组进行排序?
我尝试了以下方法,但是在排序数组时应用程序转储。

How can I sort the array using 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]];


推荐答案

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

Try making the first key lowercase.

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

这篇关于使用自定义对象对NSArray进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆