Sweeper Sweeper - 6 months ago 15
Swift Question

How to store data sequentially in Core Data?

I have an entity called

OperationEntity
. It has a to-many relationship to
OperationInput
.

enter image description here

I have a table view controller that displays all the
OperationEntity
that are saved. When the user taps on one of the cells, a segue that goes to another table view controller is performed. That table view controller displays all the associated
OperationInput
of
OperationEntity
.

In the
NSManagedObject
subclasses that Xcode has generated for me, the
availableInputs
property is declared to be of type
NSSet?
. I know that sets don't maintain the order of its elements. This means that I might save the inputs in this order:

a
b
c


But when I fetch it back, I might get it in this order instead

c
a
b


but I want the inputs to be in the same order as they were saved!

How do I solve this problem?

I have thought of adding an
id
property to
OperationInput
. Each time I save a new one, I increment the id. When I fetch it, I sort the array according to the id. But I am sure there's a better way to do it than this.

Maybe changing
NSSet?
to
NSArray?
with brute force? That can't work, can it?

It is surprising that I have not found anyone asking the question on Stack Overflow!

Answer

If you select the relationship and look in the Data Model Inspector you have an option arrangement. If you set it you will have an NSOrderedSet which maintains order.

enter image description here