Skip to content

Instantly share code, notes, and snippets.

@SheldonWangRJT
Last active February 13, 2018 21:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SheldonWangRJT/d400859ddcb4c050a6005ebff5414d00 to your computer and use it in GitHub Desktop.
Save SheldonWangRJT/d400859ddcb4c050a6005ebff5414d00 to your computer and use it in GitHub Desktop.
Something About NSUserDefaults
Something About NSUserDefaults
#iOSBySheldon
As an iOS developer, you must have heard NSUserDefaults, because, it is one of the easiest way to store something locally in users device. Even you have known it, this quick post may still help you know some details. [1]
1. NSUserDefaults is just a plist file.
Although Apple has built the interface to use it, the core of NSUserDefaults is just a plist file. The interface is pretty straight forward
UserDefaults.standard.set(<#T##value: Any?##Any?#>, forKey: <#T##String#>)
UserDefaults.standard.value(forKey: <#T##String#>)
2. Size limit?
The size limit of NSUserDefaults is just your device size, because it is a file. But Apple doesn't recommend storing a lot there.
3. What should you store in NSUserDefaults?
You'd better only store light weight, non-sensitive data in there because it is not that safe.
4. How unsafe is NSUserDefaults? [2]
Very. Even sync in iTunes will save the content in NSUserDefaults to your computer. As long as the hacker find out the path of the NSUserDefaults plist file, he can see all the data inside.
5. What type of data can you store in it?
Default types are: NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary.
And you can make your class storable after you confirm to NSCoding protocol
6. How to store data safely?
User keychain instead or encrypt the data before storing it, for example, using CommonCrypto with SHA encryption.
7. Thread performance of saving and reading of NSUserDefaults? [3]
Bad. I/O is always having the worst performance in the world of programming. Apple tries to reduce this from happening by only saving the data once a while (some say it is happening when u background the app) after you write the code
UserDefaults.standard.set(value, forKey: key)
If you wanna save the data instantly, you need to call
UserDefaults.standard.synchronize()
References Links:
[1] Apple - NSUserDefaults: https://developer.apple.com/documentation/foundation/userdefaults
[2] Q&A: https://stackoverflow.com/questions/6229038/are-nsuserdefaults-data-synced-to-itunes
[3] Q&A: https://stackoverflow.com/questions/17183183/ios-nsuserdefaults-access-before-synchronize-completion
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment