Using NSUserDefaults with Xcode 8 and iOS 10

会有一股神秘感。 提交于 2019-11-27 02:31:11

问题


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

let defaults = NSUserDefaults.standardUserDefaults()

This fails to compile. Was this class removed?

(This is a canonical Q&A pair to prevent the flood of duplicate questions)


回答1:


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

let defaults = UserDefaults.standard

This now works.

Pre-release documentation link.




回答2:


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)



回答3:


@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.



来源:https://stackoverflow.com/questions/37798426/using-nsuserdefaults-with-xcode-8-and-ios-10

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!