Saturday, 8 September 2012

NSUserDefaults



For storing data in iOS Device we have some options like NSUserDefaults, Plist file, Sqlite, Core Data.
Depending on our reqirement we switch on one of the option amongst these.

NSUserDefaults   - We store users preferences and settings here.
Plist File                - We store data in Plist if we dont have large data to persist. We store data in key-value pair. 
Core Data             - We store anything which we want to persist, we can execute predicated, fetch requests to retrieve data.
SQLite                   - We store anything which we want to persist, we can execute more complex queries directly to Database to fetch data/

Actually NSUserDefaults is a Plist file.
NSUserDefaults will store the users preferences into a Plist file into the Library/Preferences folder. So we can store whatever we can store in a Plist file.
There is no restriction on size of a Plist File. But one thing you might not forget is that when you store or read data in a Plist file whole contents of the file are loaded into memory which may effect the performance of application if you have huge data.

We can store data easily in NSUserDefaults:

[[NSUserDefaults standardUserDefaults] setInteger:1024 forKey:@"my_count"];
[[NSUserDefaults standardUserDefaults] synchronize];
Using above statements we can set int - 1024 to a key - my_count.

int myCount = [[NSUserDefaults standardUserDefaults] integerForKey:@"my_count"];
By using above statement we can fetch value for key - my_count.

Below are getter/setter method to store to or retrieve values from NSUserDefaults:
Setters Getters

setInteger:forKey: integerForKey:
setFloat:forKey: floatForKey:
setDouble:forKey: doubleForKey:
setBool:forKey: boolForKey:
setObject:forKey: stringForKey:
setObject:forKey: dataForKey:
setObject:forKey: objectForKey:
setObject:forKey: arrayForKey:
setObject:forKey: dictionaryForKey:
setObject:forKey: stringArrayForKey:

One important thing is if you are storing a Mutable Array - NSMutableArray to NSUserDefaults you will get an immutable Array - NSArray in return.
This means that values returned by NSUserDefaults are immutable.





No comments:

Post a Comment