0

I'm trying to sort an array. Inside the array are naamdeelnemer, totaalpunten etc. When I print for a check the array returns [ ]. Anyone who can help me?

import UIKit
import CoreData



var userArray:[Punten] = []

override func viewDidLoad() {

    super.viewDidLoad()

    userArray.sort { $0.naamdeelnemer! < $1.naamdeelnemer!}
    print(userArray)

    tableView.delegate = self
    tableView.dataSource = self

    self.fetchData()
    self.tableView.reloadData()
}

override func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return userArray.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    let name = userArray[indexPath.row]

    cell.textLabel!.text = name.naamdeelnemer! + "    " + String(name.totaalpunten)


    return cell
}

func fetchData() {

    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

    do {
        userArray = try context.fetch(Punten.fetchRequest())
    }
    catch {
        print(error)

    }
}
1
  • 1
    You do the sort BEFORE you fetch the content. Also, you can use a NSSortDescriptor on your request. Commented Feb 27, 2018 at 13:06

2 Answers 2

1

You can use "NSSortDescriptor" on the request while fetching the data from Core Data. Please find sample code below:

let request = NSFetchRequest<NSFetchRequestResult>(entityName: "TableName")
request.sortDescriptors = [NSSortDescriptor(key: "naamdeelnemer", ascending: true)]

Here, "TableName" is the name of table to fetch record. "naamdeelnemer" is the field on which the sorting can be done. ascending: parameter can be "true" or "false"

Sign up to request clarification or add additional context in comments.

Comments

0

You have first to fetch the data then sort them

self.fetchData()
userArray.sort { $0.naamdeelnemer! < $1.naamdeelnemer!}

However this is not CoreData like. Fetch the data passing a sort descriptor. This is much more efficient

func fetchData() {

    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    let request : NSFetchRequest<Punten> = Punten.fetchRequest()
    request.sortDescriptors = [NSSortDescriptor(key: "naamdeelnemer", ascending: true)]

    do {
        userArray = try context.fetch(request)
    }
    catch {
        print(error)

    }
}

and

userArray.sort { $0.naamdeelnemer! < $1.naamdeelnemer!}

2 Comments

I get this: Ambiguous use of 'fetchRequest()'
My bad, I uodated the answer.

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.