'Cannot remove object for key in NSUserDefaults

For some weird reason I cannot delete some of the keys in my NSUserDefaults. I am doing:

UserDefaults.standard.removeObject(forKey: "currentSelectedCategoryID")
print(UserDefaults.standard.string(forKey: "currentSelectedCategoryID"))

When I print the value, it shows the exact same value "58707" before the object was removed. I've even tried UserDefaults.standard.set(nil, forKey: "currentSelectedCategoryID") and it's doing the same thing.

Why can't I delete my key?



Solution 1:[1]

I figured it out. I was sharing my user defaults with my share extension, and I didn't remove the key for that user default object.

UserDefaults.standard.removeObject(forKey: "currentSelectedCategoryID")
if let shared = UserDefaults(suiteName: {YOUR SUITE NAME}) {
     shared.removeObject(forKey: currentSelectedCategoryID)
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 halfer