IOS development-data storage (Direct Writing, NSUserDefaults, NSkeyedArchiver)

Source: Internet
Author: User
Tags tmp folder

IOS development-data storage (Direct Writing, NSUserDefaults, NSkeyedArchiver)
Data storage (Direct Writing, NSUserDefaults, NSkeyedArchiver)
Common File Access methods in ios include:

1. directly write files. The stored objects include NSString, NSArray, NSDictionary, NSData, and NSNumber. All the data is stored in an attribute list file (*. plist file.

2. NSUeserDefaults (preference setting) is used to store application settings. files are stored in the perference directory.

3. the archive operation (NSkeyedArchiver) can store custom objects in files.

 

First, every developer should know that for an application, there is a unique sandbox corresponding to it, that is, each application cannot operate files across sandbox.

1. Obtain the sandbox path and store data by writing files

Let's look at the Code:

 

# Import "ViewController. h "@ interface ViewController () @ end @ implementationViewController-(void) viewDidLoad {[super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. [self mainOperation];}-(void) mainOperation {// obtain the cache folder path in the sandbox // method 1 // The main directory NSString * homePath = NSHomeDirectory (); // splicing path NSString * path = [homePath stringByAppendingPathComponent: @ "Library/Caches"]; // Method 2 // The first parameter is the target folder directory (achesdirectory for searching cache folders), and the second parameter is the domain for searching directories (NSUserDomainMask for searching under the user directory ), the third parameter indicates whether to expand the main directory in the result. If it is not expanded, it is displayed ~ NSArray * arr = NSSearchPathForDirectoriesInDomains (NSCachesDirectory, NSUserDomainMask, YES); // although this method returns an array, a target folder has only one directory, so there is only one element in the array. NSString * cachePath = [arr lastObject]; // or // NSString * cachePath = [arr objectAtIndex: 0]; /** // you can use the above two methods to obtain the Document folder or tmp folder path in the sandbox. // you can directly obtain NSString * tmpPath = NSTemporaryDirectory () in this way (); NSLog (@ "% @", tmpPath); ** // concatenate the path (target path). If this lotheve does not exist in the directory. plist file. This directory does not actually exist. NSString * filePath = [cachePath stringByAppendingPathComponent: @ "tese. plist "]; NSLog (@" % @ ", filePath); // create a data NSDictionary * content ={ @" Dictionary data test 1 ": @" 1 ", @ "Dictionary data test 2": @ "2", @ "Dictionary data test": @ "3 "}; // Save the data to the object in the target path (this will be automatically created if the object does not exist in this path) // writing a file using writeToFile will overwrite the original content [content writeToFile: filePath atomically: YES]; // read data (read the content of the file in a dictionary) NSDictionary * dic = [NSDictionary dictionaryWithContentsOfFile: filePath]; NSLog (@ "% @", dic);} @ end

The lotheve. plist file is added to the Library/Caches directory in the sandbox.

File Content:

2. Use NSUeserDefaults to store data

Each application has an NSUesrDefaults instance that stores application configuration information and user information, such as the user name, password, font size, and automatic logon. Data is automatically stored in the Libarary/Preferences directory of the sandbox. Similarly, this method can only access data of the NSString, NSArray, NSDictionary, NSData, and NSNumber types.

Sample Code:

 

# Import "LXXViewController. h "@ interface LXXViewController () @ end @ implementationLXXViewController-(void) viewDidLoad {[super viewDidLoad]; self. title = @ "NSUserDefaults Demo";} // click the button to save the data-(IBAction) saveData :( id) sender {// obtain the NSUserDefaults object NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults]; // Save the data without setting the path strength. NSUserDefaults stores the data in the preferences directory [userDefaults setObject: @ "Lotheve" forKey: @ "name"]; [userDefaults setObject: @ "NSUserDefaults" forKey: @ "demo"]; // save (synchronize) the data immediately (if this sentence is left blank, data will be automatically stored in the preferences directory at a certain time point in the future) [userDefaults synchronize]; NSLog (@ "data saved ");} // click the button to read the data-(IBAction) getData :( id) sender {// obtain the nsuserults ults object NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults]; // read data NSString * name = [userDefaults objectForKey: @ "name"]; NSString * demo = [userDefaults objectForKey: @ "demo"]; // print the data NSLog (@ "name = % @ demo = % @", name, demo);} @ end

 

Two buttons are set in Interface Building:

Click "save data" to view the Libarary/Preferences directory in the sandbox:

 

Data is written to the disk in plist format. Click to view data:

 

Iii. NSKeyedArchiver (archive Operation)

The main advantage of using archive to store data is that, unlike the previous two methods, the NSKeyedArchiver can only store several common data types.

Sample Code:

Note that the object class to be saved must reference the NSCoding Protocol and implement

 

- (void)encodeWithCoder:(NSCoder *)aCoder- (id)initWithCoder:(NSCoder *)aDecoder   

1. File structure:

2. Sample Code:

LXXViewController. m

 

# Import "LXXViewController. h "# import" TestPerson. h "@ interface LXXViewController () @ property (nonatomic, strong) TestPerson * p; @ end @ implementationLXXViewController-(void) viewDidLoad {[super viewDidLoad];}-(IBAction) saveData :( id) sender {// create an instance of a custom class _ p = [[TestPerson alloc] init]; _ p. name = @ "Lotheve"; _ p. age = 20; _ p. sex = @ "m"; _ p. familyMumbers = @ [@ "Father", @ "Mather", @ "Me"]; // obtain the file path NSString * docPath = [NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; // the file type can be obtained at will. The correct format is not required. NSString * targetPath = [docPath stringByAppendingPathComponent: @ "lotheve. plist "]; // Save the custom object in the specified path [NSKeyedArchiver archiveRootObject: _ p toFile: targetPath]; NSLog (@" file saved ");}

 

-(IBAction) getData :( id) sender {// obtain the file path NSString * docPath = [using (NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; NSString * targetPath = [docPath stringByAppendingPathComponent: @ "lotheve. plist "]; TestPerson * person = [NSKeyedUnarchiver unarchiveObjectWithFile: targetPath]; NSLog (@" name = % @, age = % ld, sex = % @, familyMubers = % @", person. name, person. age, person. sex, person. familyMumbers); NSLog (@ "extracted Files");} @ end

 

TestPerson. h

 

#import 
 
  @interface TestPerson : UIViewController
  
   @property (nonatomic, copy) NSString *name;@property (nonatomic, assign) NSInteger age;@property (nonatomic, copy) NSString *sex;@property (nonatomic, strong) NSArray *familyMumbers;@end
  
 

 

TestPerson. m

 

# Import "TestPerson. h "@ interface TestPerson () @ end @ implementationTestPerson-(void) viewDidLoad {[super viewDidLoad] ;}# pragma mark-NSCoding protocol method (must be implemented) // this method is called when archiving operations are performed. // In this method, you need to specify the attributes of the object to be stored-(void) encodeWithCoder :( NSCoder *) ecoder {NSLog (@ "encodeWithCoder method called"); [ecoder encodeObject: _ name forKey: @ "name"]; [ecoder encodeInteger: _ age forKey: @ "age"]; [ecoder encodeObject: _ sex forKey: @ "sex"]; [ecoder encodeObject: _ familyMumbers forKey: @ "familyMumbers"];} // This method will be called when the archive operation is performed. // In this method, you must specify the attributes of the object to be extracted-(id) initWithCoder :( NSCoder *) aDecoder {NSLog (@ "initWithCoder method called"); if (self = [super init]) {self. name = [aDecoder decodeObjectForKey: @ "name"]; self. age = [aDecoder decodeIntegerForKey: @ "age"]; self. sex = [aDecoder decodeObjectForKey: @ "sex"]; _ familyMumbers = [aDecoder decodeObjectForKey: @ "familyMumbers"];} return self ;}@ end

Click "save data" to view the Documents directory in the sandbox:

 

Click to view the file content:

 

Click "extract data" to print the result:

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.