0

I´v been hammering my head about this for hours! I am just trying to update a NSUserDefault integer value.

What is wrong with my code? Here is the exeption I get:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Wenger1.ViewController defaultsChanged]: unrecognized selector sent to instance 0x7ffe1ae2b540'

Code:

class ViewController: UIViewController {

    var fod = 0

override func viewDidLoad() {
    super.viewDidLoad()

    let prefs = NSUserDefaults.standardUserDefaults()

    // load fod
    if  prefs.stringForKey("userFOD") != nil {
        FodValue.text = String (prefs.valueForKey("userFOD"))

        // FodValue.text = String (fod)
        print("fod: \(fod)")
        }
}

@IBAction func FOD(sender: AnyObject) {
    fod =  Int(FodValue.text!)!
    //Store fod value
    let prefsFOD = NSUserDefaults.standardUserDefaults()
    prefsFOD.setInteger(fod, forKey: "userFOD") // FAIL HERE...
}
rptwsthi
  • 10,094
  • 10
  • 68
  • 109
  • 2
    what is `defaultsChanged`? Was that a previously defined function still connected to an button action? Did you get that from here http://stackoverflow.com/questions/3927402/how-to-determine-when-settings-change-on-ios ? Did you register for notifications? – luk2302 Jan 02 '16 at 17:51
  • http://stackoverflow.com/questions/29126731/swift-nsuserdefaults-setstringforkey/29126854?s=1|0.0000#29126854 – Leo Dabus Jan 02 '16 at 17:57
  • Thanks! :-) Code related to NotificationCenter caused the problem: NSNotificationCenter.defaultCenter().addObserver(self, selector: "defaultsChanged", name: NSUserDefaultsDidChangeNotification, object: nil) – Steffen Myklebust Jan 02 '16 at 18:08

2 Answers2

-1

By looking at your code I can not know what's the base issue. However, I can provide you a modified version of your code. Here you go -

var fod = 0
let userFODKey = "userFODKey"
let stUserDefaults = NSUserDefaults.standardUserDefaults()

func fetchFodFromUserDefaults() -> Int? {

    if let fod = stUserDefaults.valueForKey(userFODKey) as? Int {
        print("fod: \(fod)")
        return fod
    }
    return nil
}


func saveFodToUserDefaults(fodString: String) {

    if let fodInt = Int(fodString) {
        fod = fodInt
        stUserDefaults.setInteger(fod, forKey: userFODKey)
    }
}

To Feed the data call

saveFodToUserDefaults("yourUIElementTextString")

To fetch data call

let value: Int? = fetchFodFromUserDefaults()
BLC
  • 2,240
  • 25
  • 27
-2

You are setting integer and getting string value from NSUserDefault for the key userFOD. I think that is a mistake.

rptwsthi
  • 10,094
  • 10
  • 68
  • 109
Mayank Barnwal
  • 123
  • 1
  • 12