Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Change NSUserDefaults bool value

I want to change the character of my game when the user touches the character, so I used a NSUserDefault to store a bool and check if the user pressed on the button that will change the character.

if userDefaults.boolForKey("PBChange") == true { hero.texture = SKTexture(imageNamed: "PoolBall") hero.size = CGSize(width: 60, height: 60) }

But somehow I need to change the "PBChange" to false after changing the character.

I wanted to do this like this: userDefaults.boolForKey("PBChange").boolValue = false

But it shows me an error that I can't do that.

How can I do this??

PLEASE HELP!!

1 Answer

Hey Andrés Leal,

Why don't you just store a key value pair using a String for the key and a Bool for the value.

        NSUserDefaults.standardUserDefaults().setObject(false, forKey: "yourKey")

        // Then when you retrieve the object, type cast it as a bool
        NSUserDefaults.standardUserDefaults().objectForKey("yourKey") as? Bool

       // If you want to change the value, just set a new object for that key
       NSUserDefaults.standardUserDefaults().setObject(true, forKey: "yourKey")

Good Luck

To change it, does it has to be with the same key?

Yep, when you set a newObject using an existing key - you replace the value for that key.