Using NSUserDefaults with Xcode 8 and iOS 10

后端 未结 3 1626
无人及你
无人及你 2020-12-09 15:04

NSUserDefaults no longer appears to be a class in the iOS 10 SDK:

let defaults = NSUserDefaults.standardUserDefaults()

This fa

相关标签:
3条回答
  • 2020-12-09 15:39

    NSUserDefaults has been renamed to UserDefaults. standardUserDefaults() has been renamed to standard().

    let defaults = UserDefaults.standard
    

    This now works.

    Pre-release documentation link.

    0 讨论(0)
  • 2020-12-09 15:44

    To be more precise to use UserDefaults in Swift-3 :-

           //To save the string 
           let userDefaults = UserDefaults.standard
           userDefaults.set( "String", forKey: "Key")
    
           //To retrieve from the key
           let userDefaults = UserDefaults.standard
           let value  = userDefaults.string(forKey: "Key")
           print(value)
    
    0 讨论(0)
  • 2020-12-09 16:03

    @JAL's answer is correct, but perhaps too specific.

    Lots of API got renamed in Swift 3. Most Foundation types (NSUserDefaults among them) have both lost their NS prefix and had their methods renamed to reflect Swift 3 API Guidelines. Foundation also "replaces"* a bunch of its basic data type classes (NSURL, NSIndexPath, NSDate, etc) with Swift-native value types (URL, IndexPath, Date, etc). The method renaming also applies to any other Cocoa / Cocoa Touch APIs you use in your app.

    Dealing with these issues one by one, line by line, is a sure way to madness. The first thing you do when moving a project to Swift 3 should be to choose Edit > Convert > To Current Swift Syntax from the menu bar. This will apply all the changes at once, including cases where one line of code is affected by multiple changes (and thus addressing them individually might not get you where you think you're going).

    *I put "replaces" in quotes because the corresponding NS classes are still around for the cases where you might need them, but any API that uses them refers to the new value types instead: e.g. tableView(_:cellForRowAt:) now takes an IndexPath, not an NSIndexPath.

    0 讨论(0)
提交回复
热议问题