简体   繁体   中英

Issue with saving and retrieving array with sort by UserDefaults

Hello I am trying too add some String to the an Array and then store its values with UserDefaults , here is my code :

func addStored(urlString:String) {

        //Add URL to array and save it
        downloadedURLArray.append(urlString)

        UserDefaults.standard.set(downloadedURLArray, forKey: "storedURL")
        UserDefaults.standard.synchronize()

        var array = UserDefaults.standard.array(forKey: "storedURL")  as? [String] ?? [String]()
        array = array.sorted { $0 < $1 }
        print(array.description)

    }

I am trying to retrieve its data in ascending or descending :

array = array.sorted { $0 < $1 }

But compiler give me wrong or even random!!! values for example I am adding these item to Array :

A
B
C

The retrieved data is :

B
C
A

What is wrong ? I am I sort the array in right way ?

Try this -- >. array = array.sorted { $0.localizedCaseInsensitiveCompare($1) == NSComparisonResult.OrderedAscending

Don't call the user defaults from inside the same function. Call it from another function or the ViewDidLoad . Working Example:

var downloadedURLArray = [String]()

override func viewDidLoad() {

    addStored(urlString: "Kegham")
    addStored(urlString: "Sevan")
    addStored(urlString: "Ines")

    var array = UserDefaults.standard.array(forKey: "storedURL")  as? [String] ?? [String]()
    array = array.reversed()
    print(array.description)   //output

}


func addStored(urlString:String) {

    //Add URL to array and save it
    downloadedURLArray.append(urlString)

    UserDefaults.standard.set(downloadedURLArray, forKey: "storedURL")

}

The output is: ["Ines", "Sevan", "Kegham"]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM