参见英文答案 >
Delete all keys from a NSUserDefaults dictionary iOs13个答案如何自动清除swift中的nsuserdefault值?我已经尝试过了,但对我来说并不奏效
[[NSUserDefaults standardUserDefaults] setPersistentDomain:[NSDictionary dictionary] forName:[[NSBundle mainBundle] bundleIdentifier]];
检查已存储了多少个密钥
原文链接:https://www.f2er.com/swift/320489.htmlprint(NSUserDefaults.standardUserDefaults().dictionaryRepresentation().keys.array.count)
添加另一个关键
NSUserDefaults.standardUserDefaults().setBool(true,forKey: "justAnotherKey1") NSUserDefaults.standardUserDefaults().setBool(true,forKey: "justAnotherKey2")
检查已经存储了多少个密钥(2)
print(NSUserDefaults.standardUserDefaults().dictionaryRepresentation().keys.array.count)
现在创建一个循环来删除键的对象
for key in NSUserDefaults.standardUserDefaults().dictionaryRepresentation().keys { NSUserDefaults.standardUserDefaults().removeObjectForKey(key.description) }
检查你有多少钥匙
print(NSUserDefaults.standardUserDefaults().dictionaryRepresentation().keys.array.count)
更新:Xcode 7.2.1•Swift 2.1.1(注意NSUserDefaults不再在操场中运行,因此需要在真实项目中进行测试)
print(Array(NSUserDefaults.standardUserDefaults().dictionaryRepresentation().keys).count) NSUserDefaults.standardUserDefaults().setBool(true,forKey: "justAnotherKey2") print(Array(NSUserDefaults.standardUserDefaults().dictionaryRepresentation().keys).count) for key in Array(NSUserDefaults.standardUserDefaults().dictionaryRepresentation().keys) { NSUserDefaults.standardUserDefaults().removeObjectForKey(key) } print(Array(NSUserDefaults.standardUserDefaults().dictionaryRepresentation().keys).count)