Explain what is NSUserDefaults ?
Explain what is NSUserDefaults ?
NSUserDefaults is a class provided by Apple's Foundation framework that allows iOS applications to store small amounts of data persistently across app launches. It is essentially a key-value store designed for saving user preferences and other lightweight data. Here is a detailed explanation of NSUserDefaults:
NSUserDefaults provides a simple way to save and retrieve data such as user settings, preferences, and other small pieces of information. The data stored in NSUserDefaults persists even if the app is closed and reopened, making it ideal for maintaining user preferences and state information.
Data Persistence: Data stored in NSUserDefaults remains available across app launches. This makes it suitable for storing user settings, app configurations, and other small pieces of data that need to be retained between sessions.
Key-Value Storage: NSUserDefaults operates on a key-value basis, similar to a dictionary. You store data by associating it with a unique key, and you retrieve it using the same key.
Supported Data Types: NSUserDefaults supports a variety of data types, including:
Bool
, Int
, Float
, Double
String
Array
, Dictionary
Date
Data
URL
Standard User Defaults: The most common way to use NSUserDefaults is through the standard
property, which provides access to the shared defaults object for the app:
let defaults = UserDefaults.standard
Setting Values: You can set values in NSUserDefaults using various set
methods:
defaults.set(25, forKey: "Age")
defaults.set(true, forKey: "UseTouchID")
defaults.set("John Doe", forKey: "UserName")
Retrieving Values: Values can be retrieved using corresponding get
methods:
let age = defaults.integer(forKey: "Age")
let useTouchID = defaults.bool(forKey: "UseTouchID")
let userName = defaults.string(forKey: "UserName")
Registering Default Values: You can register default values that will be used if no value has been set for a given key:
defaults.register(defaults: ["enabledSound": true, "enabledVibration": true])
junior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào