Sunday, 9 March 2014

iPhone Development:How to use NSUserDefault in IOS







NSUserDefault IOS

NSUserDefault is a best way to save small data in your app.As we all know that IOS app stores data either on server (if data needed to be stored in a centralised place) or store it in SQlite database, though sometimes we only need to save some of the information regarding a user in our app.



In that case we can use NSUserdefault, as this class provides us a basic window to interact with default system database.The NSUserdefault class provides us with a lot of methods to save some of the common types such as integer, string, array,dictionary  etc.

Let's jump into NSUserDefault, how can we use this into our IOS app.First you need to get sharedInstance of your NSUserdefault.

    NSUserDefaults *userPrefences = [NSUserDefaults standardUserDefaults];
Now as we had our userDefault instance we can save or get values from USerDefault.You can save the value into this user-prefence default as shown below

    [userPrefences setValue:@"Name" forKey:@"String"];
    [userPrefences setInteger:1 forKey:@"Integer"];
    [userPrefences setFloat:1.0 forKey:@"Float"];

After setting value you have to call  synchronize  method to save your values to disk. Although this method automatically gets called at periodic intervals but you can use it if you want to sync/save your values right now and cannot wait for the automatic call.
 [userPrefences synchronize];

We are done with saving values to our disk.Now we want to use those saved values, we can use them as shown below

    NSString *str = [userPrefences valueForKey:@"String"];
    int num = [userPrefences integerForKey:@"Integer"];
    float numFlt = [userPrefences floatForKey:@"Float"];

No comments:
Write comments