NSUserDefaults removeObjectForKey vs. setObject:nil

后端 未结 3 891
时光说笑
时光说笑 2021-01-30 19:26

Are the following two lines equivalent?

1. [[NSUserDefaults standardUserDefaults] removeObjectForKey:@\"example key\"]

2. [[NSUserDefa

3条回答
  •  醉话见心
    2021-01-30 19:50

    Swift 3.0

    The below answer is no longer the case when I tested this. When set to nil the result is NSCFData being stored. Possibly an NSNull object reference, but I am not positive.

    To completely remove a value for a key use UserDefaults.standard.removeObject(forKey: "YourDefault")

    I tested with the following code:

    UserDefaults.standard.set(["a", "b", "c"], forKey: "MyDefaults")
    print("Test A: My saved defaults \(UserDefaults.standard.object(forKey: "MyDefaults"))")
    
    UserDefaults.standard.set(nil, forKey: "MyDefaults")
    print("Test B: My defaults set to nil \(UserDefaults.standard.object(forKey: "MyDefaults"))")
    
    UserDefaults.standard.removeObject(forKey: "MyDefaults")
    print("Test C: My defaults removed \(UserDefaults.standard.object(forKey: "MyDefaults"))")
    

提交回复
热议问题