Is there any limit in storing values in NSUserDefaults?
Solution 1:
As long as there's enough space on the iPhone/iPad, you can store NSUserDefault values. All those values is stored into a .plist file, and this file is very small, most of the time under 1 kb (unless you store a lot of data).
Solution 2:
There are limits on what types you may store: they must all be Property List objects, namely NSString
, NSNumber
, NSData
, NSArray
, and NSDictionary
. Furthermore, you may only store NSArray
and NSDictionary
if the values are also property list objects; also, all the keys of the NSDictionary
must be strings.
Note that an object like UIColor
is not on the above list. So if you want to store a color in the defaults database, you'll need to convert it into a string or data object first, then convert it back when you read the defaults.
As far as size limits, there are none that are documented, but note that all data will be stored as a property list file. The entire file is read in and written out as a whole, so if you use NSUserDefaults
to store a large amount of data that only changes in parts, you will be wasting a lot of time doing unnecessary I/O.
Solution 3:
Everyone has answered the direct question of "is there a limit?" However, I found this thread really looking to understand "how much is too much to store in UserDefaults?"
If you're looking for that answer, here's a useful thread. The responses I found helpful were to go to your project file and look at the plist file size:
5 objects is almost nothing. You'll be fine!
On my machine, I have about 28 megs of data in my user defaults. That's not causing any problems at all.
From general programming experience with arrays I would guess performance starts to rapidly decay when you get into 1000’s, depending on element size. Therefore in a program I wouldn’t have an issue storing a couple of hundred elements. This said I would probably start using a sqlite3 database or coredata, sooner rather than later if I were you.
Important to remember:
The above alleviated my concerns that my growing number of defaults (about 20-25 now) would cause problems. I use CoreData already, so I was considering which to use since my number of allowed user preferences/customizations is growing long. So, I'm going to stay with user defaults.
However, as other answers have pointed out, the file will be read and written as a whole. So reading 20 key/string dictionaries and 5 key/boolean dictionaries just to retrieve one string... not exactly ideal. Nonetheless, if it doesn't hurt performance and it saves you a ton of code, why not?