【问题标题】:Swift - Sort the content of NSSSetSwift - 对 NSSSet 的内容进行排序
【发布时间】:2017-07-08 19:11:09
【问题描述】:

我正在使用 Core Data 来获取诊所列表,诊所有关系命名为医生的关系映射到医生实体。

我的问题是,每次我获取 NSSSet 类型的医生时,记录都是随机获取的,我想使用 Doctor.name 按字母顺序对其进行排序

我尝试了以下

self.doctorList = clinic.doctors?.sortedArray(using: [NSSortDescriptor(key: "name", ascending: true)])

我哪里错了?

谢谢。

【问题讨论】:

    标签: ios swift3 nsset


    【解决方案1】:

    (NS)Set 是无序集合类型。

    要订购 Set 将其转换为具有 allObjects 属性的数组并对数组进行排序。

    self.doctorList = (clinic.doctors!.allObjects as! [Doctor]).sorted(by: { $0.name < $1.name })
    

    您甚至可以直接排序集合,但结果始终是一个数组

    self.doctorList = (clinic.doctors as! Set<Doctor>).sorted(by: { $0.name < $1.name })
    

    如果集合被声明为原生Set&lt;Doctor&gt;,无论如何你都可以省略类型转换。

    我建议将doctors 关系声明为非可选的。如果没有关联的医生,则该集合为空。但是没有医生的诊所是不太可能的;-)

    【讨论】:

    • 我收到一条错误消息,指出Cannot invoke 'sorted' with an argument list of type ((Doctor, Doctor) -&gt; Bool) 1. Expected an argument list of type '(by:(Doctor, Doctor) -&gt; Bool)'
    • 我现在收到另一个错误,上面写着Cannot invoke 'sorted' with an argument list of type (by:(Doctor, Doctor) -&gt; Bool)
    • 我拿到的当前数据夹具有很多诊所没有医生,我仍然需要存储数据。因此,在我目前的情况下,将医生关系视为非可选对我不起作用。
    • 是的,我正在尝试找出可能出现的问题。 :-(
    • 你在使用NSManagedObject子类Doctor吗?
    猜你喜欢
    • 1970-01-01
    • 2016-05-17
    • 2011-01-24
    • 1970-01-01
    • 2012-05-16
    • 2013-06-07
    • 2011-03-13
    • 2012-09-10
    • 1970-01-01
    相关资源
    最近更新 更多