0

I am making an app, and i have to store the data of four arrays (of type [(Double, Double)] and a triple og type (String, String, String). They are declared in the following class

class DataStorer {
    static var losArray = [(Double, Double)]()
    static var morgenArray = [(Double, Double)]()
    static var middagArray = [(Double, Double)]()
    static var aftenArray = [(Double, Double)]()
    static var lastMeal = ("", "", "")
}

I need to archive them when the app is closed (or other things happen, like a call), and to retrieve the data when the app needs to. The arrays have a maximum length of 18. How do i do that?

Norse
  • 628
  • 8
  • 26
  • Create a 2d array with the sub array with only 2 elements – Leo Dabus Jan 18 '16 at 19:52
  • You can use `NSUserDefaults` to store and retrieve such a data. Or in JSON like http://stackoverflow.com/questions/7172001/serialize-and-deserialize-objective-c-objects-into-json, or use `NSCoding`, etc. – Jean-Baptiste Yunès Jan 18 '16 at 20:19

1 Answers1

3

If you're not working with too many values in your arrays, you could store these into NSUserDefaults. For structured data, I tend to like creating dictionaries for the sub-values to make the property list nice and user-readable.

Saving of your tuple array to defaults is pretty easy:

let encodedValues = losArray.map{return ["0":$0.0, "1":$0.1]}
NSUserDefaults.standardUserDefaults().setObject(encodedValues, forKey:"losArray")

Loading is a little more involved, but that's only to account for all the ways that data could get corrupted in the property list:

func loadValuesFromDefaults(arrayName:String) -> [(Double, Double)] {
    guard let encodedArray = NSUserDefaults.standardUserDefaults().arrayForKey(arrayName) else {return []}
    return encodedArray.map{$0 as? NSDictionary}.flatMap{
        guard let values = $0 else {return nil}
        if let xValue = values["0"] as? Double,
               yValue = values["1"] as? Double {
                return (xValue, yValue)
        } else {
            return nil
        }
    }
}

You can replace the "0" and "1" labels with tuple-appropriate labels, if you'd like. This saves and loads an array of dictionaries, with the values of the tuple stored in a human-readable format within the array. That makes it easy to dig into the property list and both read and tweak values during development or afterward.

The various conditions in the loading function protect you against having a missing array, and array by the same name of the wrong type, and individually corrupted items within that array. I've seen nasty crashers and security issues with deserializing raw object data from property list arrays, so I use this to protect against them.

Brad Larson
  • 170,088
  • 45
  • 397
  • 571