Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to save and fetch record from NSUserDefault in iOS?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 593
    Comment on it

    Hi Readers,

    This blog includes the concept of NSUserDefault which is used to store a small amount of data in it. Now the question arises if we already have SQLite database to store data then why do we need NSUserDefault?

    The answer is other approaches are good to store a large amount of data but if we need to store a small amount of data then NSUserDefault is the perfect option. NSUserDefault not only supports the basic types but also supports plist compatible types like NSData, NSDate, NSString etc. So given below is the example of storing values in NSUserDefault and how to fetch data stored in NSUserDefault.

     


    Code to store data in NSUserDefault:-
       

    NSUserDefaults *userDef = [NSUserDefaults standardUserDefaults];
     
    NSArray *recordArrFromDef = [userDef objectForKey:@"recordArray"]; // get array from user default
     
    // array fetched from userdefault is not mutable
    // so create a mutable array
       
    NSMutableArray *mutableArr;
     
      if (!recordArrFromDef) {
    // if no array in user default create new mutable array
           mutableArr = [NSMutableArray new];
      }
    else {
     // if array present in user default then create mutable copy
           mutableArr = [recordArrFromDef mutableCopy];
       }
       
      // create mutable dictionary for record
       NSMutableDictionary *recordDic = [NSMutableDictionary new];
     
     [recordDic setObject:txtName.text forKey:@"name"];
     [recordDic setObject:txtDepartment.text forKey:@"department"];
         
      // save the dictionary to mutable array
     
     [mutableArr addObject:recordDic];
     
      // save the array to userdefaults
     
     [userDef setObject:mutableArr forKey:@"recordArray"];
       
       // synchronize
      [userDef synchronize];


     

     

    Code to fetch data from NSUserDefault:-

    
    NSArray *recordsFromUserDef = [[NSUserDefaults standardUserDefaults] objectForKey:@"recordArray"];
    NSLog(@"records in userdef %@",recordsFromUserDef);

     

    I hope this code will help you to understand the concept of NSUserDefault.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: