In short: fast / cheap? Does it make sense to store the value from NSUserDefaults in memory for faster access?
Longer: let's say I have a significant amount of values ββthat need to be saved and read from NSUserDefaults; with the need to often receive (read) these values.
In the snippet below, I initialize the private stored property and keep it synchronized with the corresponding NSUserDefaults value - so when I need to read it, I read the property.
If the default read directly is fast, I would obviously delete the private property. But I'm not so sure about that. Is it fast?
private var _loggedIn = NSUserDefaults.standardUserDefaults().boolForKey("loggedIn") public var loggedIn: Bool { get { return _loggedIn } set { _loggedIn = newValue NSUserDefaults.standardUserDefaults().setBool(newValue, forKey: "loggedIn") NSUserDefaults.standardUserDefaults().synchronize() } }
Clarification for future readers: the question is about reading, and not about recording / synchronization, which (as indicated in the answers) is neither fast nor cheap.
.synchronize() is called on the setter for a good reason - in my particular case, it is important that it synchronizes immediately, so I sacrifice performance for logical integrity. In general, you should consider whether you need to call it β or let the system choose the right time for recording.
.. Actually, now when I look at it, I see that storing the saved property, as in the fragment, will ensure logical integrity (if access from other places is via getter, and not directly from userDefaults). Therefore, I can also avoid synchronizing .
source share