fa_devlpr
fa_devlpr

Reputation: 57

Store Struct in NSUserdefault swift

Please I need help with this code, any assistance you can offer will be much appreciated.

I currently have a struct where that I use to save values before putting them in a table but when the app is restarted the values disappear, I have tried using nsuserdefaults (but nsuserdefaults does not save structs). Is there another method to save these values for even when the app is restarted??

NSObject for SAVING TO NSUSERDEFAULTS

import UIKit

var plannerMgr : plannerManager = plannerManager()

struct plan 
{
    var planName = "Un-Named"
    var planDescription = "Un-Described"
}

var pNameArray = NSMutableArray()
var pDescArray = NSMutableArray()

class plannerManager: NSObject {

    var plans = [plan]()


    func addPlan(pName: String, pDesc: String) {

        plans.append(plan(planName: pName, planDescription: pDesc))

        pNameArray.addObject(pName)
        pDescArray.addObject(pDesc)

        defaults.setObject(pNameArray, forKey: "pNameArray")
        defaults.setObject(pDescArray, forKey: "pDescArray")
        defaults.synchronize()

    }

}

...Bit for GETTING FROM NSUSERDEFAULTS

func getPlans() {
        if let tempArray1 = defaults.objectForKey("pNameArray") as? NSMutableArray {
            if (tempArray1.count > 0) {
                pNameArray = tempArray1
            }
        }

        if let tempArray2 = defaults.objectForKey("pDescArray") as? NSMutableArray {
            if (tempArray2.count > 0) {
                pDescArray = tempArray2
            }
        }

        for name1 in pNameArray {
            for desc1 in pDescArray {
                println("add Plan: name1 = \(name1) && desc1 = \(desc1) **")
                addPlan(name1 as! String, pDesc: desc1 as! String)
            }
        }
    }

My main issue is when i call the second func (getPlans) the app crashes, and the console mentions something about using a mutable method with an immutable object.

Upvotes: 0

Views: 742

Answers (1)

Andrew
Andrew

Reputation: 15377

Even if you save a mutable array to NSUserDefaults, you aren't guaranteed to get a mutable array back.

You need to get a .mutableCopy() of the array to ensure you are manipulating a mutable array.

if let tempArray1 = defaults.objectForKey("pNameArray") as? NSArray {
    if (tempArray1.count > 0) {
       pNameArray = tempArray1.mutableCopy() as! NSMutableArray
    }
}

Ensure to change this for both tempArray1 and tempArray2.

Upvotes: 2

Related Questions