0

As far as I could find out, there is no easy random query function in parse. Is there a way to shuffle the objects after I queried them?

query.findObjectsInBackgroundWithBlock { (objects, error) -> Void in

        if (error == nil) {
            // shuffle objects here?
            PFObject.pinAllInBackground(objects, withName:"Card", block: nil)

Any ideas? Thanks!

EDIT: I think the problem is at another point. When I add like in the suggest post (thanks for that) the extension for shuffling, it works like a breeze!

BUT!

query.findObjectsInBackgroundWithBlock { (objects, error) -> Void in

        if (error == nil) {

            println(objects)

            var shuffled = objects.shuffled()

            println(shuffled)

            PFObject.pinAllInBackground(shuffled, withName:"Card", block: nil)

As you can see, I pin the objects to the local storage.

On my next view I pull this data again out of the storage:

var query = PFQuery(className: "Card")
query.fromLocalDatastore()
query.findObjectsInBackgroundWithBlock { (objects, error) -> Void in

     if (error == nil){
        println("from local store: \(objects)")

And here I have again the data in the same order as they are saved in the database... There are no shuffled items at all.

Isn't that strange?

user1555112
  • 1,897
  • 6
  • 24
  • 43
  • possible duplicated: http://stackoverflow.com/questions/24026510/how-do-i-shuffle-an-array-in-swift – Javier Flores Font Mar 17 '15 at 15:11
  • I think the problem is that when you pull them from the local database or the parse database, either way, there's some sort of query. I believe this defaults to be sorted by `updatedAt`. You'll need to re-sort your objects each time you retrieve them and then sort them in memory. – Logan Mar 17 '15 at 15:41
  • Thanks Logan! That seems to be the right issue :( I don't think there is a way to prevent this kind of default sorting? – user1555112 Mar 19 '15 at 15:13

1 Answers1

0

Just take the objects and use a shuffle-method like provided in this answer on the objects:

var shuffledObjects = shuffle(objects) 
Community
  • 1
  • 1
Christian
  • 22,585
  • 9
  • 80
  • 106