Original blog, reproduced please specify
Blog.csdn.net/hello_hwc
The data persistence storage of iOS is divided into many kinds
- Normal file, plist
- Nsuserdefaults
- CoreData
- KeyChain
This article explains the use of nsuserdefaults
Standarduserdefaults
Most of the time, Standarduserdefaults is used to save the data, which is a shared userdefaults, which means that the same userdefaults is accessed anywhere in the program.
Write Data
Swift Code
var userdefaults = NSUserDefaults.standardUserDefaults() userdefaults.setBool(truefor"KEYBOOL") userdefaults.setObject("String"for"KSTRING")
Note that the data written by the above code is not immediately synced to the file, but is saved in the cache, which increases the rate (the file IO is inefficient). If you want to sync now
userdefaults.synchronize()
If it is not very necessary to synchronize to the database, it is recommended not to call the synchronous method every write, because it is relatively slow.
Read the data
var str = userdefaults.objectForKey("KSTRING"as? String varbool = userdefaults.boolForKey("KEYBOOL")
Userdefaults for App Group services
Such userdefaults are shared and used in the following two scenarios
- App Suite, which means you need to share data between two apps
- App extension, sharing data between extension and his contain app. Typical is the Input method program, in the contain app settings, the keyboard style will change.
How to use-take extension as an example
Writing data in the contain app
OC Code
NSUserDefaults *shared = [[NSUserDefaults alloc]initWithSuiteName:@"group.yourcompanyname.yourappname"]; setforKey:@"KDICFORWIDGET"]; setObject:@"1234"forKey:@"KSTRINGFORWIDGET"]; [shared synchronize];
Read data in extension
NSUserDefaults *shared = [[NSUserDefaults alloc]initWithSuiteName:@"group.yourcompanyname.yourappname"];NSMutableDictionary *dic = [shared objectForKey:@"KDICFORWIDGET"];NSString *str = [shared objectForKey:@"KSTRINGFORWIDGET"]
IOS Data Persistence Nsuserdefaults