NSUserDefaults Lose Newly Saved Data if App Killed Within 10 Seconds - ios

I'm looking for a faster way to save user preferences than the NSUserDefaults. I've found that if the app is killed within around 10 seconds of writing to NSUserDefaults, it will not be saved permanently. I use the defaults to save paths to custom ring tones, paths to custom images, map coordinates, and basically just user defined preferences. Is using core data the better option? SQLite? What's accepted as the fastest and most lightweight?

You need to be sure to call synchronize to save the data immediately.
[[NSUserDefaults standardUserDefaults] synchronize];
From Apple's class reference:
Because this method is automatically invoked at periodic intervals,
use this method only if you cannot wait for the automatic
synchronization (for example, if your application is about to exit) or
if you want to update the user defaults to what is on disk even though
you have not made any changes.
And to answer your second question, it really depends on how much data you want to store. NSUserDefaults is designed to store very small amounts of data (for preferences) like the state of a toggle switch, etc. You can get away with storing the paths to images and ring tones here but it isn't exactly advisable. By that I mean you can, but probably shouldn't.
Core Data is a much better approach if you plan on storing many of these paths as it is very scalable and performs very well. So overall, if you need to store a lot of data, user Core Data, or as another alternative store the paths in a plist in the documents directory.

Related

Singletons vs Core Data

This question is not about the technical problem, but rather the approach.
I know two more or less common approaches to store the data received from the server in your app:
1) Using managers, data holders etc to store the data. They are most often some kind of singleton and are used to store the models received from the server. (E.g. - the array of the posts/places/users) Singletons are needed to be able to access the data from any screen. I think the majority of apps uses this approach.
2) Using Core Data (or maybe Realm) as in-memory storage. This approach avoids having singletons, but, I guess, it is a bit more complex (and crash risky) to maintain and support.
How do you store data and why?
P.S. Any answers would help. But big "thank you" for detailed ones, with reasons.
The reason people opt to use Core Data/Relam/Shark or any other iOS ORM is mainly for the purpose of persisting data between runs of the app.
Currently there are two ways of doing this, for single values and very small (not that I encourage it) objects you can use the UserDefaults to persist between app launches. For a approach closer to a database, infact in the case of Core Data and SharkORM, they are built on top of SQLite, you need to use an ORM.
Using a manager to store an array of a data models will only persist said models for the lifetime of the app. For example when the user force quits the app, restarts their device or in some circumstances when iOS terminates your app, all that data will be lost permanently. This is because it is stored in RAM which is volatile memory, rather than in a database on the disk itself.
Using a database layer even if you don't specifically require persistence between launches can have its advantages though; for instance SharkORM allows you to execute raw SQL queries on your objects if you don't want to use the built in powerful query builder. This can be useful to quickly pull the model you are interested in rather than iterating through a local array.
In reply to your question, how do I store data?
Well, I use a combination of all three. Say for instance I called to an API for some data which I wanted to display there and then to the user, I would use a manager instance with an array to hold the data model.
But on the flipside if I wanted to store that data for later or if I needed to execute a complex query on it, I would store it on disk using Shark.
If however I just wanted to store whether or not the user had seen my on boarding flow I would just persist a boolean value into UserDefaults.
I hope this is detailed enough for you.
CoreData isn't strictly "in-memory". You can load objects into your data model and save them into their context, then they might actually be on disk and out of main memory, and they can easily be brought back via fetch requests.
Singletons, on the other hand, do typically stay in main memory all the time until the user terminates the app. If you have larger objects that you are storing in some data structure (e.g. full resolution images when all you really needed was a thumbnail), this can be quite a resource hog.

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 !

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.

Why is NSUserDefaults used in 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.

Resources