×

iOS NSUserDefaults Class


What is NSUserDefualts Class ?

Suppose you want to store some data which you think will be useful throughout your app and you want to save it then NSUserDefualts Class is the most easiest way to save application data and properties. Even if you close your application that saved data will be available to you throughout your app. You might think where this data will be stored . Right ? The objects will be saved in what is known as the iOS "defaults system ".


With NSUserDefaults you can save objects from following class types :

1) NSNumber

2) NSDictionary

3) NSArray

4) NSData

5) NSDate

Example :-

In this example we save string value of name , integer value of age and image in NSUserDefaults.

1) Create a new Xcode Project, File > New > Project > Single View Application > Enter Project Name > Create



2) Now copy this code in ViewController.h file to create User Interface for sample App

#import "ViewController.h"

@interface ViewController ()<UIImagePickerControllerDelegate,UIActionSheetDelegate,UINavigationControllerDelegate>
{
    UIImageView *imageUser;
    UIButton *imageButton;
    UITextField *textFieldName;
    UITextField *textFieldAge;
}
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    UILabel *labelUserDfaults = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMidX(self.view.frame)- 60, 40, self.view.frame.size.width, 28)];
    [self.view addSubview:labelUserDfaults];
    labelUserDfaults.textColor = [UIColor colorWithRed:38.0/255.0 green:84.0/255.0 blue:162.0/255.0 alpha:1.0];
    labelUserDfaults.text = @"NSUserDefualts";
    labelUserDfaults.font = [UIFont fontWithName:@"helvetica-bold" size:20.0];
    
    
    imageButton = [[UIButton alloc]initWithFrame:CGRectMake(40, CGRectGetMaxY(labelUserDfaults.frame) + 12, 120, 120)];
    [self.view addSubview:imageButton];
    [imageButton addTarget:self action:@selector(imageButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    imageButton.layer.borderWidth = 1.0;
    imageButton.layer.cornerRadius = 3.0;
    
    
    imageUser = [[UIImageView alloc]initWithFrame:CGRectMake(40, 40, 40, 40)];
    [imageButton addSubview:imageUser];
    imageUser.image = [UIImage imageNamed:@"camera"];
    
    
    textFieldName = [[UITextField alloc]initWithFrame:CGRectMake(CGRectGetMaxX(imageButton.frame) + 20, CGRectGetMaxY(labelUserDfaults.frame) + 12, 180, 32)];
    [self.view addSubview:textFieldName];
    textFieldName.placeholder = @"Name";
    textFieldName.font = [UIFont fontWithName:@"Helvetica-bold" size:13.0];
    textFieldName.layer.borderWidth = 1.0;
    textFieldName.layer.borderColor = [UIColor grayColor].CGColor;
    textFieldName.textAlignment = NSTextAlignmentCenter;
    textFieldName.layer.cornerRadius = 3.0;
    [textFieldName becomeFirstResponder];
    
    
    textFieldAge = [[UITextField alloc]initWithFrame:CGRectMake(CGRectGetMaxX(imageButton.frame) + 20, CGRectGetMaxY(textFieldName.frame) + 12, 180, 32)];
    [self.view addSubview:textFieldAge];
    textFieldAge.placeholder = @"Age";
    textFieldAge.font = [UIFont fontWithName:@"Helvetica-bold" size:13.0];
    textFieldAge.layer.borderWidth = 1.0;
    textFieldAge.layer.borderColor = [UIColor grayColor].CGColor;
    textFieldAge.textAlignment = NSTextAlignmentCenter;
    textFieldAge.layer.cornerRadius = 3.0;
    textFieldAge.keyboardType = UIKeyboardTypeNumberPad;
    
    
    UIButton *buttonSave = [[UIButton alloc]initWithFrame:CGRectMake(CGRectGetMaxX(imageButton.frame) + 20, CGRectGetMaxY(textFieldAge.frame) + 12, 180, 32)];
    [self.view addSubview:buttonSave];
    [buttonSave setTitle:@"Save Data" forState:UIControlStateNormal];
    [buttonSave addTarget:self action:@selector(buttonSaveClicked) forControlEvents:UIControlEventTouchUpInside];
    [buttonSave setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    buttonSave.backgroundColor =  [UIColor colorWithRed:38.0/255.0 green:84.0/255.0 blue:162.0/255.0 alpha:1.0];
    buttonSave.layer.cornerRadius = 3.0;
    
    
    // Prepopulate the saved data
    [self prepopuateData];
    
}

-(void)prepopuateData
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    textFieldName.text = [defaults stringForKey:@"name"];
    textFieldAge.text =  [NSString stringWithFormat:@"%ld", (long)[defaults integerForKey:@"age"]];
    
    NSData *imageData = [defaults dataForKey:@"image"];
    UIImage *imageUs = [UIImage imageWithData:imageData];
    
    [imageButton setImage:imageUs forState:UIControlStateNormal];
    imageUser.image = imageUs;
}

#pragma mark - Actions
-(void)imageButtonClicked
{
    [self.view endEditing:YES];
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:@"Gallery",@"Camera",nil];
    [actionSheet showInView:self.view];
}


-(void)buttonSaveClicked
{
    UIImage *imageUs = imageUser.image;
    NSData *imageData = UIImageJPEGRepresentation(imageUs, 100);
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:textFieldName.text forKey:@"name"];
    [defaults setInteger:[textFieldAge.text integerValue] forKey:@"age"];
    [defaults setObject:imageData forKey:@"image"];
    
    [defaults synchronize];
    
    NSLog(@"Saved");
}


#pragma mark - UIActionSheetDelegate

- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex)
    {
        case 0:
        {
            [self galleryBtnPressed];
        }
            break;
        case 1:
        {
            [self cameraBtnPressed];
        }
            break;
            
        default:
            break;
    }
}


- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    
    UIImage *chosenImage = info[UIImagePickerControllerEditedImage];
    imageUser.image = chosenImage;
    
    
    [imageButton setImage:chosenImage forState:UIControlStateNormal];
    [picker dismissViewControllerAnimated:YES completion:NULL];
}

- (void)galleryBtnPressed
{
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.allowsEditing = YES;
    imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    imagePickerController.delegate = self;
    [self presentViewController:imagePickerController animated:YES completion:nil];
}


- (void)cameraBtnPressed
{
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.allowsEditing = YES;
    imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
    imagePickerController.delegate = self;
    [self presentViewController:imagePickerController animated:YES completion:nil];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end

3) Output :-


Short explanation of code:-

In viewDidLoad method we created two textFields, one ImageButton and one save button. When user clicks save button NSUserDefaults reference is created. Then we stored textFieldName's text value with key "name". textFieldAge's integer value inside key "age" and image with the help of imageData in key image.

-(void)buttonSaveClicked
{
    UIImage *imageUs = imageUser.image;
    NSData *imageData = UIImageJPEGRepresentation(imageUs, 100);
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:textFieldName.text forKey:@"name"];
    [defaults setInteger:[textFieldAge.text integerValue] forKey:@"age"];
    [defaults setObject:imageData forKey:@"image"];
    
    [defaults synchronize];
    
    NSLog(@"Saved");
}

Now to get the stored value from NSUserDefaults we used stringForKey method to get name, integerForKey to get age and dataForKey to get imageData then assigned those value to their respective textFields and imageView.

-(void)prepopuateData
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    textFieldName.text = [defaults stringForKey:@"name"];
    textFieldAge.text =  [NSString stringWithFormat:@"%ld", (long)[defaults integerForKey:@"age"]];
    
    NSData *imageData = [defaults dataForKey:@"image"];
    UIImage *imageUs = [UIImage imageWithData:imageData];
    
    [imageButton setImage:imageUs forState:UIControlStateNormal];
    imageUser.image = imageUs;
}

At first time when you try to select image from gallery by clicking image button app gets crashed. This is because you did not given the permissions to your app to use Library or Camera. So search for .plist file and paste this

For Photo Library,
In key column paste this,
Privacy - Photo Library Usage Description

Select type  String

In Value column ,
$(PRODUCT_NAME) photo use
 
For Camera Use,
In key column paste this,
Privacy - Camera Usage Description

Select type  String


In Value column ,
$(PRODUCT_NAME) camera use