Ordered Sets and Core Data (NSOrderedSet)
Asked Answered
G

3

13

I have a list of share prices with the properties dateTime and value.

Currently I am sorting the share prices when fetching them using a sort descriptor.

Now, I would like to change my code and store them in already sorted order to faster retrieve the most current share price (dateTime = max).

I am inserting the share prices one by one using

SharePrice *priceItem= [NSEntityDescription insertNewObjectForEntityForName:@"SharePrice" inManagedObjectContext:context];

How can I sort the share prices right after inserting them using a sort descriptor on dateTime?

Or would I need to convert it to a NSMutableOrderedSet and use sortUsingComparator:?

Thank you!

Gradin answered 25/4, 2013 at 14:46 Comment(0)
B
25

Ordered property on CoreData

Mark the Ordered checkbox of your property in your CoreData model.

Also be sure to set the CoreData automatic migration in your AppDelegate (options dictionary when creating PersistentStore). This way CoreData will be able to make this change without data lost.

Beals answered 27/4, 2013 at 7:46 Comment(3)
How can I reorder an existing ordered set in the database?Gradin
I think you can't do it automatically. You can make a function to order based in some criteria like order or date. If you change a NSSet to NSArray in your CoreData Model, I assume you didn't have a order before, so it will get the "allObjects" from the old NSSet and add it to your array.Beals
How do you specify what to base on for sorting? In OP's case, based on dateTime?Lacework
R
3

i would like to add to the accepted answer, if you have a NSSet, it must be changed to a NSOrderedSet after selecting the ordered checkbox

Racemose answered 6/6, 2016 at 6:29 Comment(1)
Thanks, this is detail about changing to an NSOrderedSet is what I came here to find.Moores
C
0

I'm not sure how using an NSMutableOrderedSet would affect the underlying sqlite database. It is nice to think that it would store it in the order of the set, but the underlying implementation is a blackbox and I don't think there's any guarantee that it would work consistently, if it worked at all.

If it's a performance gain you are looking for, I would think adding an index to that attribute would be the best approach.

Chilli answered 25/4, 2013 at 14:56 Comment(5)
With that said, mysql does support clustered indexes (which affects the sort on disk). I am not sure if it is exposed in CoreData, but that is something you could look into.Chilli
I have the attribute indexed and do the sort with each fetch. However, I need to improve the performance and would like to store the items in sorted order.Gradin
What does MySQL have to do with anything here?Afterbody
@TomHarrington Pretty sure they mean SQLite, or they've had too much Ale.Deipnosophist
Wow, Tom...Isn't it obvious I meant sqlite? If you gave me a downvote because of that, shame on you.Chilli

© 2022 - 2024 — McMap. All rights reserved.