2

I have an array that is loaded from MYSQL database using PHP and converting to JSON, the data get loaded into the table, but now I want to sort this data, how can I do this? I would like to sort them by latest time = in my object array.

JSON Result got with NSURLSession:

(
        {
        id = 8;
        time = "2015-07-24 17:12:00";
        title = "World is full of good people!";
    },
        {
        id = 10;
        time = "2015-07-24 18:44:30";
        title = "One morning, when Gregor Samsa woke from troubled dreams, he found himself transformed in his bed into a horrible vermin. He lay on his armour-like back, and if he lifted his head.";
    }
)

I read some questions/answers on stackoverflow.com and people are saying I should use sorted on my array, but I think that method is gone in swift 2.

This is what I get once i try it arr.sorted

'NSArray' does not have a member named 'sorted'

I find an apple sorting document, but couldn't find any good answer to describe on how to use it.

2
  • That might depend from the code you're using to do that. It would be better to post the relevant part of your code so that it might be easier to spot what's wrong Commented Jul 25, 2015 at 5:58
  • sort isn't gone, it's just not a global function anymore. It's now a function on array. Commented Jul 25, 2015 at 6:49

1 Answer 1

4

Once you have the data in a Swift array and the date stored as NSDate (which is not what you show above), you can use sortInPlace, for example:

    s.sortInPlace { (a, b) -> Bool in
         return a.time.timeIntervalSinceReferenceDate < b.time.timeIntervalSinceReferenceDate
    }
Sign up to request clarification or add additional context in comments.

2 Comments

The date do get converted to NSDate in cellForIndexPath, so basically use the sortInPlace there?
cellForRowAtIndexPath is asking for data for a particular cell. It should be already sorted when you get there. You should sort it right after you retrieve it from the database. Or even better, sort it in the MySql database query and pass it to the mobile device already sorted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.