Sorting an array that's filled from CoreData

427 Views Asked by At

I have a text field in which users can input numerical values and store them to core data as strings. In turn I am retrieving those values and have stored them in an array as ints. What I want to do is sort that array by the order that the user stores the values because I am trying to graph the values to see their trend over time. Right now the values are populating my graph in a totally random manner from all I can tell.

var client: Client! = nil
var weights = []

func getWeights() {
        var assessmentWeights: NSSet = client.assessment.valueForKey("weight") as NSSet
        var weightSet: NSSet = assessmentWeights.valueForKey("integerValue") as NSSet
        weights = weightSet.allObjects
        println(weights)
    }

Any help is appreciated! :)

1

There are 1 best solutions below

9
On

If you already have a timestamp associated with each weight entry you can either (a) create a NSFetchRequest with sort descriptor or you can (b) sort the values you already have in NSSet

Since I do not see much code to go with, here's an example of option (b):

var weights = [Int]();
if let entries = client.assessment.allObjects as? [Assessment] {
    let sorted = entries.sorted {
        return $0.timestamp.compare($1.timestamp) == .OrderedAscending
    }
    for assessment in sorted {
        if let intValue = assessment.weight.toInt() {
            weights.append(intValue)
        }
    }
}

return weights

Having said this, the best option, in my opinion, is to store weight value as a numeric value and use NSFetchRequest (result type .DictionaryResultType) with sort descriptor on timestamp to get the values you want.