user3766930 user3766930 - 1 month ago 5
Swift Question

I'm checking if the object in nsdictionary is nil and I'm getting wrong response - why?

I want to store in

NSUserDefaults
information if user clicked the button or not.
I have two buttons, one has +1 value, the other one -1.

When user presses one of those two buttons, I'm doing this:

if (self.defaults.objectForKey("pressedButtons") == nil){
let currentButtonId:[String:String] = [self.pressedButtons:vote]
self.defaults.setObject(currentButtonId, forKey: "pressedButtons")
self.defaults.synchronize()
} else {
var pressedButtons:[String:String] = self.defaults.objectForKey("pressedButtons") as! [String:String]
pressedButtons[self.button_id] = vote
self.defaults.setObject(pressedButtons, forKey: "pressedButtons")
self.defaults.synchronize()
}


in the code above
vote
is a String value that can be either
"1"
or
"-1"
.

Now, when user comes back to the panel, I'm checking if he already pressed the button or not. This is how I check it:

if (self.defaults.objectForKey("pressedButtons") != nil){

if (self.defaults.objectForKey("pressedButtons")![currentButtonId] != nil) {
print("user already pressed")
print(self.defaults.objectForKey("pressedButtons")![currentButtonId])
} else {
print("USER didn't press the button yet")
}
} else {
print("USER didn't press the button yet for sure")
}


the output that I always see is:

user already pressed
nil


Since this line:

print(self.defaults.objectForKey("pressedButtons")![currentButtonId])


prints
nil
, why am I seeing the message that user pressed the button?

Answer

Take this object always typecasted as [String:String] while fetching

let variable = self.defaults.objectForKey("pressedButtons") as! [String:String]

Now this is a variable of type [String:String]

Now fetch your value accordingly

This doesn't know that self.defaults.objectForKey("pressedButtons") is a object with type [String:String]. So, typecast it first and then use. So self.defaults.objectForKey("pressedButtons")![currentButtonId] seems to be nil