Search code examples
arraysswiftfor-loopcore-datashuffle

need to save a shuffled order in core data


I am attempting to shuffle the order of the array in core data. Right now the code shuffles the order it attempts to save the shuffle order but when I reload the class the original order is still there.

What I am am attempting to do is in the code below. YESR is being printed int he debug section.

var songs = [Song]()
var index = Int()
var singer: Singer?

override func viewDidLoad() {
    super.viewDidLoad()
 
    if let singer = singer {
        songs = DataManager.shared.songs(singer: singer)
    }
    tableView.reloadData()
    
    
}
 @objc func shuffleButtonPressed() {
    print("shuffle")

    // Shuffle the songs
    songs.shuffle()

    // Update the 'order' attribute for each song
    for (index, song) in songs.enumerated() {
        song.order = Int16(index)
    }

    do {
        try DataManager.shared.save() // Assuming 'DataManager.shared' is your Core Data manager
        tableView.reloadData()
        
        print("yesr")
    } catch {
        // Handle error while saving
        print("Error saving shuffled songs: \(error)")
    }
}`

Solution

  • It's not clear how the underlying persistence layer has been implemented or the design of the Song class. The sort order should be inferred when fetching the data, almost certainly by specifying a SortDescriptor.

    However as you are storing the index of each song within it's own data type you can use that when you retrieve the data:

    songs = DataManager.shared.songs(singer: singer).sorted{$0.order < $1.order}
    

    If you can make Song conform to Comparable based on its order property you can just use .sorted()