Search code examples
swiftcore-datansarraynsset

Convert NSSet into an Array


I'm storing data in a CoreData entity that uses relationships. By default a toMany type relationship will be of typeNSSet. In order to load this NSSet into a tableview in the order in which the items where added to this NSSet I need to convert it to an array. How do I go about achieving this?

enter image description here

NSManaged Subclass generated:

extension Node {

    @nonobjc public class func fetchRequest() -> NSFetchRequest<Node> {
        return NSFetchRequest<Node>(entityName: "Node")
    }

    @NSManaged public var value: String?
    @NSManaged public var children: NSSet?
    @NSManaged public var parent: Node?


    @objc(addChildrenObject:)
    @NSManaged public func addToChildren(_ value: Node)

    @objc(removeChildrenObject:)
    @NSManaged public func removeFromChildren(_ value: Node)

    @objc(addChildren:)
    @NSManaged public func addToChildren(_ values: NSSet)

    @objc(removeChildren:)
    @NSManaged public func removeFromChildren(_ values: NSSet)
}

Note: As CloudKit doesn't support ordered relationships, I can't use ordered arrangement as a part of the solution.


Solution

  • My suggestion is to declare the relationship as non-optional native Swift type

    @NSManaged public var children: Set<Node>
    

    To get an array just sort the set. This is pretty easy with a Swift Set. As a set is unordered by definition you have to do that anyway to get a fixed order. Assuming you have a dateAdded attribute you can write

    let sortedChildren = children.sorted{$0.dateAdded > $1.dateAdded}