Why is NSUserDefaults used in iOS? - ios

I am new to iOS development and Mobile app development in general, I have decent knowledge about Objective C and MVC patterns to be used and I have never done any Mac development.
I am struggling to understand what NSUserDefaults is for?
We already have something like PList which stores data as XML and we have SQLite which is lightweight DB for such devices.
Then why do we have it?
Is it an alternative simple key-value storage for our app in the same way we have different types of storage on the cloud like an RDBMS and a key-value based NoSQL store etc ?
For NSUserDefaults, Apple docs say that :-
"Applications record such preferences by assigning values to a set of parameters in a user’s defaults database"
What do they mean by user's default database?
My guess is that, like in any multi-user operating system we have various user accounts and in the same way in Mac as well we might be having multiple users each having a database from where applications would load saved preferences for that user.
So like Mac OS X, does iOS also have multiple users and depending upon whichever is logged in NSUserDefaults picks his/her preferences?
Please tell me if I am wrong.

One thing that hasn't been mentioned yet: NSUserDefaults supports all basic scalar (float, int, BOOL) types, as well as the plist-compatible types: NSData, NSString, NSNumber, NSDate, NSArray, and NSDictionary. (You mentioned plists as an alternative--NSUserDefaults is just a front-end to a standard plist file in the application's Preferences folder.) This makes it easy to create persistent storage for your application state in just a few lines of code. Even better, if you implement NSCoding on your model objects, you can archive them into an NSData and put them in NSUserDefaults:
NSData* data = [NSKeyedArchiver archivedDataWithRootObject:arrayOfModelObjects];
[[NSUserDefaults standardUserDefaults] setObject:data forKey:kDefaultsKeyModelObjects];
and restoring your app data is as simple as
- (void)viewDidLoad
{
NSData* data = [[NSUserDefaults standardUserDefaults] objectForKey:kDefaultsKeyModelObjects];
arrayOfModelObjects = [[NSKeyedUnarchiver unarchiveRootObject:data] retain];
// error checking, tell UI to load the new values, etc...
}
(kDefaultsKeyModelObjects is a string constant you've defined somewhere. Always put your NSUserDefaults keys in one place! Having a typo in a key name can take hours to debug. :)
If you used, e.g., SQLite to store your application data, you have to write a lot of code to move your model data in and out of the database. That makes sense if you're dealing with a lot of data, need efficient searching, etc.; but if it's, say, a list of servers in a networking app, it's easier and cleaner to throw them in NSUserDefaults.
One last thing: NSUserDefaults is great for prototyping. Even if you know you're going to need a SQLite store eventually, you can start out using NSUserDefaults as a quick-and-easy persistent store, and get your UI working and your data model fleshed out before writing a bunch of database code.
So like Mac OS X, does iOS also have multiple users and depending upon
whichever is logged in NSUserDefaults picks his/her preferences ?
Nope, on iOS the defaults plist is in the application's Library/Preferences folder, not in a user-specific folder like it is on OS X. I can't imagine iOS will ever have multiple logins, but you never know. If it did, they'd have to make separate defaults plists for different users.

NSUserDefaults are used to save small portions of data the App is dependent on to run correctly, while other approaches are good to store bigger amounts of data, that the app work with.
NSUserDefaults makes is incredible easy, as you don't have to worry about files, entities, fetches,…. It is all done in one line.

It's originally for storing settings, but does seem to get (ab)used for a lot of other things if the questions on SO are anything to go by. The "point" of it is that it provides a single-line data persistence and retrieval method for a wide range of data types.
There is no multi-user configuration (yet?) on iOS (have you ever had to sign in to your iPhone?) that is built in to NSUserDefaults, but because OS X and iOS are built on the same foundation, the same class is used for both operating systems.

iOS is a single-user OS. Hence, NSUserDefaults is used differently in OSX and iOS.
In iOS, you normally use NSUserDefaults to save application preferences and/or user data on the "iOS defaults system". Data saved in the defaults system will be persistent at all time even when you reboot the iOS device. As a matter of fact, even when the user updates the application.
You typically want to use NSUserDefaults to save application preferences/settings. Any other massive data such as game data or realtime calculations should be save in CoreData or sqllite in the documents directory.

NSUserDefaults stored values for only your application.
Note - It is not meant to serve as a replacement for a traditional store for data (Core Data, SQLite, Property Lists, etc are meant for storing application data). What NSUserDefaults is meant for is for specific key value pairs.
For example, I use it to store an authenticated user's networkid and full name once the login process is done. Upon session timeout or logout, I clear those values. For this NSUserDefaults shines.

Related

Do NSUserDefaults and SQL tables need to checked for prexistence on the phone?

I have several instances in my iOS app where I utilize NSUserDefaults to store very basic things, like small string arrays and integer values that I would like to persist in my app. I also utilize a SQL database (via FMDB) to store some things locally that are larger (like a series of messages). I run into no issues on the simulator, but my question is for a live app should I be checking for existence of SQL tables or NSUserDefaults that already have the names I am trying to assign? ie is the NSUserDefaults app specific, and is the internal SQL library also app specific... is it possible for me to, by chance, create a SQL table/NSUserDefault key for my app which happens to share the same name as a table/key for another app without any issues?
Apps on iOS are entirely sandboxed; your app's file directories are separated from those of other apps, and the same goes for NSUserDefaults. You won't need to worry about overlapping.

iCloud data backup and restore strategy

Don't know if this type of question is ok here but I'll ask anyway.
I have an iOS iCloud Core Data application that works decently well (though I think it does need some synchronization tweaking) and am considering allowing the user so save a copy of the database to iCloud drive in a UIDocument. This would allow the user to possibly segment the database manually and load only the portions they want to use at the moment as well as provide peace of mind considering that the data may include some insurance claims data.
I'm weighting several alternatives to allow this to happen.
Option 1 is to just create an iOS based save and restore process which, when triggered, would dump the database (maybe at max 1000 objects) into an NSArray of NSDictionary objects (one dictionary per row) and then JSONize the NSArray into NSData and save it in a new UIDocument on iCloud drive. A restore process would list possible archives to restore and then allow the user to pick one. The restore process would do the reverse of the save process.
Option 2 would be to create Mac App to handle the save/restore process which would allow the user to save the archives on the user's Mac. This seems a lot less difficult though it would require a set of apps working together. The mechanism would be similar as option 1 but the data would go to a file specified in a standard Mac file system pick screen.
Personally, I'd like to do both of them but before I start I want to make sure that there's not an easier way than dumping the entire SQL database into an NSArray of NSDictionaries.
A complicating factor is that the database contains images which are in the database as NSData. I could string-ize the NSData, add it into the NSDictionary build, then let the JSON process do it's thing.
I'm just fine with proceeding this way but I wanted to make sure I wasn't overlooking some type of Apple method of doing this in an easier way.
Another thought that came to me was maybe using some sort of SQLite utility to do save and restore locally in one session which would then replicate the results across all of the devices via iCloud. Again, sounds like more of a Mac answer to me but I don't really know.
Again, any suggestions would be great.
iCloud supports synchronizing CoreData databases. See this article for some more information.
Also, you might consider looking at CloudKit for storing this data directly in iCloud, so it can be accessed on multiple devices.

NSUserDefaults or a backend?

I have to ship a simple app with a very tight deadline so I have no time to learn anything othen than what I know (meaning learning Core Data for example). Would it fine to use NSUserDefaults to store data for my app? It's almost like a check list app where users have list of items with some data accompanying each item.
Other than that I would be using a service like Parse which I can handle thanks to having built my last app with it.
Would Apple reject an app if you use NSUserDefaults for something other than settings/preferences?
Thanks!
From Apple's documentation:
The NSUserDefaults class provides a programmatic interface for interacting with the defaults system. The defaults system allows an application to customize its behavior to match a user’s preferences. For example, you can allow users to determine what units of measurement your application displays or how often documents are automatically saved. Applications record such preferences by assigning values to a set of parameters in a user’s defaults database. The parameters are referred to as defaults since they’re commonly used to determine an application’s default state at startup or the way it acts by default.
[...]
Values returned from NSUserDefaults are immutable, even if you set a mutable object as the value. For example, if you set a mutable string as the value for "MyStringDefault", the string you later retrieve using stringForKey: will be immutable.
In other words, this is not the place to store mutable application data.
If the checklist data is going to be modified by end users (i.e. adding new items, or editing the text of the items on the checklist) it really would be worthwhile to learn how to use Core Data. Over the years it really has become very easy to learn and use.
You can find a great series of Core Data tutorials at http://code.tutsplus.com/series/core-data-from-scratch--cms-653
If you're looking for something that's been updated for iOS 8 and Swift (although they're mainly syntax changes for the new language), you can check out http://www.raywenderlich.com/85578/first-core-data-app-using-swift.
Apple wouldn't reject even if you unnecessarily burden NSUserDefault. But users of your App will definitely uninstall it or OS will kill it if app crashes or hangs their iPhone.
NSUserDefault : is a fast way to access the data. it stores in (key,value) pair and lives as long as your app is installed in phone. Usually session based small amount of data is supposed to be stored in it. Not ur entire database.
Database (CoreData or Sqlite) : Behind the seen Coredata is also a sqlite with objects talking to each other(Think in terms of model instead of tables if using Coredata).
I simple suggest you use Coredata if your data by any chance is big or expected to get big. CoreData wont take much time.
Yes, you can store data in NSUserDefaults, which will be the quick and dirty method to store data locally.
You could use Core Data, though I prefer to just use FMDB and write my own SQLite statements. You could also use NSFileManager and just read and write everything to a JSON file. Parse will probably be overkill if all you are doing is storing a list of check list objects.
Go for NSUserDefault fro now !
When the App is submitted fro approval, look at SQlLite. this will be useful for the next projects.
Parse... sure but make sure it's not overkilling especially if you have limited amount of data
Good Luck !

Preventing NSUserDefaults from iCloud Backup

There are three ways to write persistently to the device in iOS that I'm aware of:
NSUserDefaults
Custom Objects - Archived and Written to a PATH in NSDocuments
SQLite
Apple provide a mechanism to prevent iCloud backups with #2 i.e.
- (BOOL)addSkipBackupAttributeToItemAtURL:(NSURL *)URL
I use NSUserDefaults to store three images but to adhere to iOS Data Storage Guidelines -
How do I prevent Backups with iCloud with NSUserDefaults?
This question has been asked several times on SO but there is no clear comprehensive answer yet.
Is there a such a function or do I have to change storing images using method #2. I was hoping something convenient like:
- (BOOL)addSkipBackAttributeForStandardUserDefaultsKey:(NSString *)
exists.
There's no mechanism for this. NSUserDefaults is not intended to be used for saving app data. It's there to hold user preferences and other settings the app needs, but isn't intended as a full data persistence system.
It's not accurate to say that this "...[Apple's] mechanism for storing data can't adhere to it's own guidelines" because that's not the purpose of this API. In this case specifically, if those images should not be backed up, then that's absolute evidence that user defaults is the wrong place to store them.
You should save the images to files. If you have UIImage, this is simple. UIImage conforms to NSCoding, so it's easy to convert to/from an NSData. And NSData includes convenience methods to read/write objects to files. If the file names might change, you could reasonably put the file names in user defaults. If the file names are known in advance and can't change, then there's no reason to store them.

iOS NSUserDefaults standardUserDefaults

I've a conceptual question — do I always have to use the standardUserDefaults API when accessing NSUserDefaults?
I am saving a lot of settings/flags/NSCoding info in my app for a variety of things. But for some of these things, it doesn't feel natural for me to be bothering the standardUserDefaults. I am wondering if I could potentially create a new NSUserDefaults entity for managing certain type of information that I want to store.
Just for an example — I am using some background NSURLSessionDownloadTasks and I want to save some relationship data between the downloadTask and the actual user for which the download task was initiated. I am saving that data to NSUserDefaults. I just am not sure if accessing NSUserDefaults for this (and other things) is the way to go!
[Maybe I didn't explain this right. Sorry!]
NSUserDefaults is not the right solution for what you described.
NSUserDefaults is actually for a very narrow and particular purpose. It is mainly meant to interact with users, let them set their preferences and get those preferences persisted.
It is not meant to be used as any type of general purpose storage.
For what you want, you can always use a usual NSDictionary etc for that. If you need it to be accessible from multiple places, leave it on the application delegate or create a singleton class. If you need it to be persisted across runs, use something like SQLite.
One thing you could do is use [[NSUserDefaults alloc] initWithSuiteName:] to create separate NSUserDefaults storage.
Just doing [[NSUserDefaults alloc] init] will get you the same storage as standardUserDefaults.
As I understand, there's no need to specifically create a new user defaults file for the specific purpose of classification of data.
The NSUserDefaults can be as large as any system file and the data dump can be adjusted accordingly. In case one needs a new defaults, please see Catfish_Man's answer. Also, this is specifically for the case when you deal with a certain group of apps.

Resources