Search code examples
swiftios8nsset

Best Practice for saving many to one in order using NSSet?


I am new to Swift and was wondering if anyone can give me some tips on how to store data in a Core Data NSSet sorted for an item that has the relationship one to many in order. I have a book class (the many) and I have a shelf class (the one) that has an NSSet of books in it.

class Shelf: NSManagedObject {

    @NSManaged var books: NSSet
}

class Book: NSManagedObject {
    @NSManaged var title: String
}

I can add books to the shelf and that works, but the order seems to be random every time I try to access them instead of the order I added them. I want the result in the order I added it to be retained. Is there a way to do this without adding another class like bookOnShelf to store the position?

var booksInOrder = myShelf.books.AsAnyObject as [Book]
for(var i = 0; i < mySlelf.books.count; i++)
{
   output(booksInOrder[i])
}

Solution

  • Update your CoreData model to enable the "Ordered" attribute of the relationship.

    You'll also want to change the property declaration in your code to:

        @NSManaged var books: NSOrderedSet