Alex Marchant
Alex Marchant

Reputation: 2510

Swift bind to Objective-C boolean value

I've got a button shuffleButton that you can click to toggle shuffling.

Since I like to store that property when the app is closed I've bound a custom property selected, which is a Bool, from the shuffleButton to the user defaults.

shuffleButton.bind("selected", toObject: NSUserDefaultsController.sharedUserDefaultsController(), withKeyPath: "values.shuffle", options: nil)

This only works one way though. If I set the user default property the button updates.

NSUserDefaults.standardUserDefaults().setValue(true, forKey: "shuffle")

// test it out
println(NSUserDefaults.standardUserDefaults().valueForKey("shuffle"))
=> 1
println(shuffleButton.selected)
=> true

But if I update the selected property on the button the user default is not updated.

shuffleButton.selected = true

// test it out
println(NSUserDefaults.standardUserDefaults().valueForKey("shuffle"))
=> 0
println(shuffleButton.selected)
=> true

Any idea why? Is the Swift Bool value not being bridged properly to Objective-C?

Upvotes: 1

Views: 1818

Answers (2)

karthikPrabhu Alagu
karthikPrabhu Alagu

Reputation: 3401

Try using setBool to set bool value because bool is not an object,thats why iOS providing this method to save bool value. You no need to bridge shuffleButton.selected will accept the swift bool value, everything is rewritten in swift language (check the class reference) following sample is working fine

    let defs = NSUserDefaults.standardUserDefaults();
    var k = true;
    defs.setBool(k, forKey: "bool");
    defs.setDouble(2.5, forKey: "foo");
    defs.synchronize();
    var ud = defs.doubleForKey("foo");
       var bo = defs.boolForKey("bool");
    println("default = \(ud) bool =\(bo)");
    shuffleButton.selected = bo;

Upvotes: 1

Renish Dadhaniya
Renish Dadhaniya

Reputation: 10752

When you update(Change Value) SuffleButton then also update your NSUserdefault.

  shuffleButton.selected = true

 NSUserDefaults.standardUserDefaults().setBool(shuffleButton.selected as Bool!, forKey: "shuffle")
 NSUserDefaults.standardUserDefaults().synchronize()

Upvotes: 0

Related Questions