Article source: blog.csdn.net/enuola/arti…

NSUserDefaults is a great way to store lightweight local data, such as user names, passwords, etc. I prefer NSUserDefaults. So the next time I log in, I’m going to be able to read the last login information directly from NSUserDefaults.

Because if you’re using your own plist file or whatever, you have to display your own file, create your own file, read your own file, which is a lot of trouble, but if you’re using NSUserDefaults, you don’t bother with all that stuff, you just read strings, you just read them.

NSUserDefaults supports the following data formats: NSNumber (Integer, Float, Double), NSString, NSDate, NSArray, NSDictionary, and BOOL. Very practical!

NSUserDefaults is very convenient and very easy to read. Here is an example of how to use it: (PS: you can also refer to the official documentation for more details)

The viewController.h file contains several controls for displaying stored data:

[cpp]  view plain copy

  1. #import <UIKit/UIKit.h>  
  2.   
  3. @interface ViewController : UIViewController  
  4. {  
  5.       
  6.     IBOutlet UILabel *txtInteger;  
  7.     IBOutlet UILabel *txtFloat;  
  8.     IBOutlet UILabel *txtDouble;  
  9.     IBOutlet UILabel *txtNSString;  
  10.     IBOutlet UILabel *txtNSDate;  
  11.     IBOutlet UILabel *txtNSArray;  
  12.     IBOutlet UILabel *txtNSDictionary;  
  13. }  
  14.   
  15. @end  

The two most important methods in viewController.m are:

SaveNSUserDefaults: Used to save various types of data into NSUserDefaults

ReadNSUserDefautls: Used to read various types of data from NSUserDefaults. Call these two methods in viewDidLoad and you’ll see what happens

[cpp]  view plain copy

  1. #import “ViewController.h”  
  2.   
  3. @interface ViewController ()  
  4.   
  5. @end  
  6.   
  7. @implementation ViewController  
  8.   
  9. – (void)viewDidLoad  
  10. {  
  11.     [super viewDidLoad];  
  12.   
  13. [self saveNSUserDefaults]; // Call this method to store various data in NSUserDefautls, as defined below
  14. [self readNSUserDefaults]; Call this method to read various data from NSUserDefautls, as defined below
  15. }  
  16.   
  17. – (void)viewDidUnload  
  18. {  
  19.     [txtNSString release];  
  20.     txtNSString = nil;  
  21.     [txtNSDate release];  
  22.     txtNSDate = nil;  
  23.     [txtNSArray release];  
  24.     txtNSArray = nil;  
  25.     [txtNSDictionary release];  
  26.     txtNSDictionary = nil;  
  27.     [txtInteger release];  
  28.     txtInteger = nil;  
  29.     [txtFloat release];  
  30.     txtFloat = nil;  
  31.     [txtDouble release];  
  32.     txtDouble = nil;  
  33.     [super viewDidUnload];  
  34.     // Release any retained subviews of the main view.  
  35. }  
  36.   
  37. – (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation  
  38. {  
  39. return (interfaceOrientation ! = UIInterfaceOrientationPortraitUpsideDown);
  40. }  
  41.   
  42. – (void)dealloc {  
  43.     [txtNSString release];  
  44.     [txtNSDate release];  
  45.     [txtNSArray release];  
  46.     [txtNSDictionary release];  
  47.     [txtInteger release];  
  48.     [txtFloat release];  
  49.     [txtDouble release];  
  50.     [super dealloc];  
  51. }  
  52.   
  53. // Save data to NSUserDefaults
  54. -(void)saveNSUserDefaults  
  55. {  
  56.     NSString *myString = @”enuola”;  
  57.     int myInteger = 100;  
  58. Float myFloat = 50.0 f;
  59. Double myDouble = 20.0;
  60.     NSDate *myDate = [NSDate date];  
  61.     NSArray *myArray = [NSArray arrayWithObjects:@”hello”, @”world”, nil];  
  62.     NSDictionary *myDictionary = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@”enuo”, @”20″, nil] forKeys:[NSArray arrayWithObjects:@”name”, @”age”, nil]];  
  63.       
  64. // Store all of the above data in NSUserDefaults
  65.     NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];  
  66. // setObject:forKey: // setObject:forKey:
  67.     [userDefaults setInteger:myInteger forKey:@”myInteger”];  
  68.     [userDefaults setFloat:myFloat forKey:@”myFloat”];  
  69.     [userDefaults setDouble:myDouble forKey:@”myDouble”];  
  70.       
  71.     [userDefaults setObject:myString forKey:@”myString”];  
  72.     [userDefaults setObject:myDate forKey:@”myDate”];  
  73.     [userDefaults setObject:myArray forKey:@”myArray”];  
  74.     [userDefaults setObject:myDictionary forKey:@”myDictionary”];  
  75.       
  76. // Synchronizing storage to disk is recommended, but not required
  77.     [userDefaults synchronize];  
  78.       
  79. }  
  80.   
  81. // Read data from NSUserDefaults
  82. -(void)readNSUserDefaults  
  83. {  
  84.     NSUserDefaults *userDefaultes = [NSUserDefaults standardUserDefaults];  
  85.       
  86. // Read data into each label
  87. // Read data of type int
  88.     NSInteger myInteger = [userDefaultes integerForKey:@”myInteger”];  
  89.     txtInteger.text = [NSString stringWithFormat:@”%d”,myInteger];  
  90.       
  91. // Reads data of float type
  92.     float myFloat = [userDefaultes floatForKey:@”myFloat”];  
  93.     txtFloat.text = [NSString stringWithFormat:@”%f”,myFloat];  
  94.       
  95. // Read data of type double
  96.     double myDouble = [userDefaultes doubleForKey:@”myDouble”];  
  97.     txtDouble.text = [NSString stringWithFormat:@”%f”,myDouble];  
  98.       
  99. // Read NSString data
  100.     NSString *myString = [userDefaultes stringForKey:@”myString”];  
  101.     txtNSString.text = myString;  
  102.       
  103. // Read data of NSDate date type
  104.     NSDate *myDate = [userDefaultes valueForKey:@”myDate”];  
  105.     NSDateFormatter *df = [[NSDateFormatter alloc] init];  
  106.     [df setDateFormat:@”yyyy-MM-dd HH:mm:ss”];  
  107.     txtNSDate.text = [NSString stringWithFormat:@”%@”,[df stringFromDate:myDate]];  
  108.       
  109. // Read an array of data of type NSArray
  110.     NSArray *myArray = [userDefaultes arrayForKey:@”myArray”];  
  111.     NSString *myArrayString = [[NSString alloc] init];  
  112.     for(NSString *str in myArray)  
  113.     {  
  114.         NSLog(@”str= %@”,str);  
  115.         myArrayString = [NSString stringWithFormat:@”%@  %@”, myArrayString, str];  
  116.         [myArrayString stringByAppendingString:str];  
  117. //        [myArrayString stringByAppendingFormat:@”%@”,str];  
  118.         NSLog(@”myArrayString=%@”,myArrayString);  
  119.     }  
  120.     txtNSArray.text = myArrayString;  
  121.       
  122. // Read data of type NSDictionary
  123.     NSDictionary *myDictionary = [userDefaultes dictionaryForKey:@”myDictionary”];  
  124.     NSString *myDicString = [NSString stringWithFormat:@”name:%@, age:%d”,[myDictionary valueForKey:@”name”], [[myDictionary valueForKey:@”age”] integerValue]];  
  125.     txtNSDictionary.text = myDicString;  
  126. }  
  127.   
  128. @end  

Ok, run it and you can see that all the data in the XIB file has been bound?

\

So when you run it again, you can call [self saveNSUserDefaults] in viewDidLoad; This line is commented out to let the program read directly without storing the data, and it finds that previously saved data can still be read to the interface.

Hee hee, it is very simple, so you can realize the storage of data.

Here is the principle:

One question you might ask is: where does NSUserDefautls store data?? I did not show the specified path?? Confused…

The data stored in NSUserDefaults will still be there the next time the program runs, where does it store the data? How can it be cleared?

In fact, it is stored in a plist file built into the application, which can be seen by path.

For example, this is your program sandbox (the sandbox) position/UsersLibrary/Application Support/iPhoneSimulator / 4.1 / Applicati * * * * * / 29788 e40 – AF47-45 a0-8 e92-3 ac0f501b7f4 /, (this is the location of the corresponding on the MAC application) And then there’s the /Library/Prefereces, and there’s a plist file that stores your userDefaults. If you want to delete it, use removeObjectForKey or delete the sandbox, which is your app, and reinstall it.

\

The iPhone sandbox model has four folders, what are they, where the permanent data store is usually placed, and what is an easy way to get the path to the emulator.

Documents, TMP, app, Library.

(NSHomeDirectory ()),

Manually saved files are in the Documents file

The files saved in Nsuserdefaults are in the TMP folder

\

1. Documents directory: You should write all de application data files to this directory. This directory is used to store user data or other information that should be backed up periodically.

2. Appname. app directory: This is the application package directory, which contains the application itself. Because the application must be signed, you cannot make changes to the contents of this directory at run time, otherwise the application may not start.

Library directory: This directory has two subdirectories: Caches and Preferences. The Preferences directory contains the application’s preference files. Instead of creating a preference file directly, you should use the NSUserDefaults class to get and set your application’s preferences. Caches directory: For application-specific support files that hold information needed to start the application again.

4. TMP directory: This directory is used to store temporary files that are not needed during application startup.

NSString *homeDir = NSHomeDirectory(); The method of 2, access to the Documents directory path: NSArray * paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory NSUserDomainMask, YES). NSString *docDir = [paths objectAtIndex:0]; The method of 3, get Caches directory path: NSArray * paths = NSSearchPathForDirectoriesInDomains (NSCachesDirectory NSUserDomainMask, YES); NSString *cachesDir = [paths objectAtIndex:0]; NSString *tmpDir = NSTemporaryDirectory(); 5. The method to obtain the file path of the resource in the application package: for example, the method to obtain the path of an image resource (apple.png) in the application package: NSString *imagePath = [[NSBundle mainBundle] pathForResource:@ “apple” ofType:@ “PNG”]; UIImage *appleImage = [[UIImage alloc] initWithContentsOfFile:imagePath]; The mainBundle class method in the code is used to return an object representing the application package.

Several directories in the iPhone Sandbox:

[cpp]  view plain copy

  1. // Get the sandbox home directory path
  2. NSString *homeDir = NSHomeDirectory();  
  3. // Get the Documents directory path
  4. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);  
  5. NSString *docDir = [paths objectAtIndex:0];  
  6. // Get the Caches directory path
  7. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);  
  8. NSString *cachesDir = [paths objectAtIndex:0];  
  9. // Obtain the TMP directory path
  10. NSString *tmpDir =  NSTemporaryDirectory();  

[cpp]  view plain copy

  1. // Get the path to an image resource (apple.png) in the current package
  2. NSString *imagePath = [[NSBundle mainBundle] pathForResource:@”apple” ofType:@”png”];  
  3. UIImage *appleImage = [[UIImage alloc] initWithContentsOfFile:imagePath];  

Example:

NSFileManager* fm=[NSFileManager defaultManager]; if(! [fm fileExistsAtPath:[self dataFilePath]]){

/ / here is to set the file path saved [FM createDirectoryAtPath: [self dataFilePath] withIntermediateDirectories: YES attributes: nil error:nil];

NSArray *files = [FM subpathsAtPath: [self dataFilePath]];

NSData *data = [FM contentsAtPath:[self dataFilePath]];

// or NSData *data = [NSData dataWithContentOfPath:[self dataFilePath]]; }

\