Converting Swift Array to NSData for NSUserDefaults.StandardUserDefaults persistent storage

I’m trying to get my head around Swift (after being relatively competent with Obj-C) by making a small app. I would like to use NSUserDefaults to persistently save a small amount of data but I am having problems.

I initialise an empty array of tuples like this:

  • Why is it always possible to access the .0 element of an optional tuple in Swift?
  • How to loop over struct properties in Swift?
  • In Swift can I use a tuple as the key in a dictionary?
  • Single-element parethesized expressions/tuples vs common use of parentheses
  • Swift encode tuple using NSCoding
  • Converting a C char array to a String
  • var costCategoryArray: [(name:String, defaultValue:Int, thisMonthsEstimate:Int, sumOfThisMonthsActuals:Int, riskFactor:Float, monthlyAverage:Float)]=[]
    

    When the array has an entry, I want to save the array to NSUserDefaults with standard Swift code such as this:

    NSUserDefaults.standardUserDefaults().setObject(costCategoryArray, forKey: "financialData")
    NSUserDefaults.standardUserDefaults().synchronize()
    

    I get an error saying that the tuple array doesn’t conform to the AnyObject class. So I tried to turn it into NSData:

    var myNSData: NSData = NSKeyedArchiver.archivedDataWithRootObject(costCategoryArray)
    var myUnarchivedData: Array = NSKeyedUnarchiver.unarchiveObjectWithData(myNSData)
    

    …but I get the same error during the conversion to NSData. The object being held by my array doesn’t conform to AnyObject. I’ve also tried at each stage to make it immutable by using:

    let immutableArray = costCategoryArray
    

    Ive also tried creating a class instead of using tuples which I understood would make it comply with AnyObject:

    class costCategory : NSObject {
        var name : String
        var defaultValue : Int
        var thisMonthsEstimate : Int
        var sumOfThisMonthsActuals : Int
        var riskFactor : Float
        var monthlyAverage : Float
    
    
        init (name:String, defaultValue:Int, thisMonthsEstimate:Int,     sumOfThisMonthsActuals:Int, riskFactor:Float, monthlyAverage:Float) {
            self.name = name
            self.defaultValue = defaultValue
            self.thisMonthsEstimate = thisMonthsEstimate
            self.sumOfThisMonthsActuals = sumOfThisMonthsActuals
            self.riskFactor = riskFactor
            self.monthlyAverage = monthlyAverage
        }
    }
    

    But the new error is:

    “Property list invalid for format: 200 (property lists cannot contain objects of type ‘CFType’)”

    What is the problem with an array of tuples? Why can’t I store an array of class objects? I feel like I need some expert advice as so far everything I try to do with Swift is pretty much incompatible…

    Thanks!

    2 Solutions Collect From Internet About “Converting Swift Array to NSData for NSUserDefaults.StandardUserDefaults persistent storage”

    Anything you are archiving to NSData and back needs to implement the NSCoding protocol. I found that in addition, my Swift class had to extend NSObject. Here is a quick example of a Swift class that encodes and decodes:

    class B : NSObject, NSCoding {
        var str : String = "test"
    
        required init(coder aDecoder: NSCoder) {
            str = aDecoder.decodeObjectForKey("str") as String
        }
    
        override init() {
        }
    
        func encodeWithCoder(aCoder: NSCoder) {
            aCoder.encodeObject(str, forKey: "str")
        }
    }
    
    // create an Object of Class B
    var b : B = B()
    
    // Archive it to NSData
    var data : NSData = NSKeyedArchiver.archivedDataWithRootObject(b)
    
    // Create a new object of Class B from the data
    var b2 : B = NSKeyedUnarchiver.unarchiveObjectWithData(data) as B
    

    value of “financialData” should be in quotes:

    NSUserDefaults.standardUserDefaults().setObject("costCategoryArray", forKey: "financialData")
    NSUserDefaults.standardUserDefaults().synchronize()