views:

561

answers:

3

Is there a way to select a fixed number of random entries from a Core Data store? I am just getting started with Core Data and have been stuck on this problem for quite some time.

As a last resort, I could query a large selection of entries into memory and then randomly select a fixed number.

Also, is there a way to specify custom SQL statements to be executed on the Core Data store? I realize that this would be highly unlikely since the underlying implementation of the store could be an XML file as well.

+1  A: 

Mmm... maybe

[[[managedObjectsContext registeredObjects] allObjects] objectsAtIndex:r]

where r is random int between 0 and the number of objects minus one? Not efficient at all but quick and easy.

EDIT: if you want to pick the random object between a selection of your objects then create a fetch request that describes your object selection and do the same as above with the query results:

[[[managedObjectsContext executeFetchRequest:request error:&error] objectAtIndex:r]
IlDan
Not all the managed objects in my store are of the same type. I want a random entry of a particular type. Picking a random object among all the registered objects might not work.I am using identity fields in my entries. Fortunately, I know that that there are no missing identity values. I just randomly select identity values and specify an NSPredicate using the same. Though this is working for now, there has to be a better way.Thanks for your help though.
Buzzy
A: 

With regards to your second question, that is one of the points of Core Data, to abstract away the underlying data store. Using NSPredicate and NSExpressions to build a fetch request, or storing one in the data model is the only way to query the store.

Don
A: 

Not sure, but I think Core Data puts data into NSSets for you. So you might be able to use -[NSSet anyObject]. I haven't tested that or anything.

Jonathan Sterling
-anyObject is random from the developers' point of view in that you have no control over it, but in reality it's just whichever object is at the root of the internal data store, so it will consistently be the same object until the contents of the set are changed.
TALlama
Aha! Thanks for clarifying.
Jonathan Sterling