Hello. I have a basic question. Say you have a NSFetchRequest which you want to perform on a NSManagedObjectContext. If the fetch request doesn't have any sort descriptors set to it explicitly, will the objects be random every time, or are they going to be spit out into an array in the order they were added to the Managed Object Context initially? I can't find this answer anywhere in the documentation. Thanks.
views:
546answers:
3The order may not be "random every time" but as far as I know you cannot/should not depend on it. If you need a specific order, then use sort descriptors.
No, they're not guaranteed to be ordered. You might happen to see consistent ordering depending on what type of data store you use (I've never tried), but it's not something you should depend on in any way.
It's easy to order by creation date though. Just add a date attribute to your entity, initialize it to the current date in awakeFromInsert
, and specify that sort descriptor in your fetch.
I see two questions here: will it come out in the same ordering every time? And, is that ordering on insertion order?
It comes out in set order, which is in some ordering. Note that NSSet is just an interface and there are private classes that implement NSSet. That means that while some instances of NSSet you get back if you call allObjects against it might return them in some consistent ordering, it's almost assuredly in hash ordering as sets are almost universally implemented as hashed dictionaries.
Since the hashing algorithm is highly variable depending on what is stored and how it's hashed, you might "luck out" that it comes out in the same ordering every time, but then be caught off guard another time when something changes very slightly.
So, technically, it's not really random and it could be in some stable ordering.
To the second question, I would say it's almost assuredly NOT in insertion order.
Marc's suggestion for handling awakeFromInsert is a good one, and what you would want.