Friday, 4 April 2014

NSUserDefaults storing persistent data in iOS App - Xcode.

We can use Sqlite, p-List, and NSFile for storing User Data.
But they are little complex, if we just want store small data we can use NSUserDefaults.

Note: The values are removed on app deletion and the values are not affected when an application is updated.



Eg://Set the values

[[NSUserDefaults standardUserDefaultssetBool:NO      forKey:@"myBoolKey"];

[[NSUserDefaults standardUserDefaults] setObject:@"myString" forKey:@"myStringKey"];

[[NSUserDefaults standardUserDefaults] setInteger:1      forKey:@"myIntegerKey"]; 


//Fetch the values
[[NSUserDefaults standardUserDefaults] boolForKey:@"myBoolKey"];

 [[NSUserDefaults standardUserDefaults]   valueForKey:@"myStringKey"];

[[NSUserDefaults standardUserDefaults] integerForKey:@"myIntegerKey"];


To remove/reset all the values:

NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];
[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];



To remove one the values:
 [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"myKey"];



//you can also do all these work just by little effort. Now Pass the value and related key.

+(void)saveTheContent:(id)content withKey:(NSString*)stringKey
{
    NSUserDefaults *defaultUser = [NSUserDefaults standardUserDefaults];
    [defaultUser setObject:content forKey:stringKey];
    [defaultUser synchronize];
    
}


+(void)removeContentForKey:(NSString*)stringKey
{
    NSUserDefaults *defaultUser = [NSUserDefaults standardUserDefaults];
    [defaultUser removeObjectForKey:stringKey];
    [defaultUser synchronize];
}



No comments:

Post a Comment