IOS data storage-01 Basic Introduction

Source: Internet
Author: User

IOS data storage-01 Basic Introduction

1. Apply sandbox

 

1. What is sandbox?

 

 

Each iOS app has its own application sandbox (the application sandbox is the application folder), which is isolated from other file systems. The application must be in its own sandbox. Other applications cannot access the sandbox.

 

2. Apply the sandbox Structure

Application Package:Contains allResource fileAndExecutable files

Documents:Save the persistent data generated when the application is running. This directory is backed up when the iTunes synchronization device is running. For example, a game application can save a game archive in this directory. Save relatively important data Tmp:Save the temporary data required for running the application, and then delete the corresponding files from the directory after use. When the application is not running, the system may also clear files in the directory. This directory is not backed up when you synchronize devices with iTunes. Store unimportant and big data. Library/Caches:Save the persistent data generated when the application is running. This directory is not backed up when the iTunes synchronization device is running. Non-important data that generally has a large storage space and does not need to be backed up Library/Preference:Save all the preference Settings of the app. the iOS Settings app searches for the app Settings in this directory. This directory is backed up when the iTunes synchronization device is running. This directory is managed by the system, and does not need to be managed. It is usually used to store some basic software configuration information, such as remembering passwords and automatic logon.

3. common methods for obtaining the sandbox directory

Sandbox directory:NSString * home = NSHomeDirectory ();

Documents: (2 types)

1. splice the "Documents" string with the directory using the sandbox

NSString * home = NSHomeDirectory ();

 

NSString * documents = [home stringByAppendingPathComponent: @ "Documents"];

// It is not recommended because the new version of the operating system may modify the directory name.

2. Use the NSSearchPathForDirectoriesInDomains Function

 

// NSUserDomainMask indicates that it is found in the user folder

// YES indicates the Tilde "~" in the expanded path

NSArray * array = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES );

// In iOS, there is only one directory that matches the input parameters. Therefore, this set has only one element.

NSString * documents = [arrayObjectAtIndex: 0];

Tmp:

 

NSString * tmp = NSTemporaryDirectory ();

 

Library/Caches(Two methods similar to statements)
1. concatenate a "Caches" string using the mountain root directory

2. Use the NSSearchPathForDirectoriesInDomains function (change the 2nd parameters of the function to NSCachesDirectory)

Library/Preference:
Access the settings in this directory through the NSUserDefaults class

2. Common iOS Data Storage Methods

 

The XML property list (plist) archive Preference (Preference setting) uses plist to store data in essence, but it is simpler to use (no need to pay attention to files, folder paths, and names)
NSKeyedArchiver archive (NSCoding) stores any object directly as the file SQLite3. When a large amount of Data is stored, it uses Core Data to encapsulate SQLite.

1. attribute list

Property list: the property list is an XML file. The extension name is plist.

 

If the object is of the NSString, NSDictionary, NSArray, NSData, or NSNumber type, you can use writeToFile: atomically: to directly write the object to the attribute list file.

Archive NSDictionary

 

// Encapsulate data into a dictionary NSMutableDictionary * dict = [NSMutableDictionary dictionary]; [dict setObject: @ "hen" forKey: @ "name"]; [dict setObject: @ "15013141314" forKey: @ "phone"]; [dict setObject: @ "27" forKey: @ "age"]; // persists the dictionary to Documents/stu. in the plist file, [dict writeToFile: path atomically: YES];
Restore NSDictionary

 

// Read Documents/stu. plist content, instantiate NSDictionaryNSDictionary * dict = [NSDictionary dictionaryWithContentsOfFile: path]; NSLog (@ "name: % @", [dict objectForKey: @ "name"]); NSLog (@ "phone: % @", [dict objectForKey: @ "phone"]); NSLog (@ "age: % @", [dict objectForKey: @ "age"]);

 

2. preference settings

Each application has an NSUserDefaults instance to access preference settings.
Get user preference settings save information
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];[defaults setObject:@"itcast" forKey:@"username"];[defaults setFloat:18.0f forKey:@"text_size"];[defaults setBool:YES forKey:@"auto_login"];

Read preference settings

 

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];NSString *username = [defaults stringForKey:@"username"];float textSize = [defaults floatForKey:@"text_size"];BOOL autoLogin = [defaults boolForKey:@"auto_login"];

 

Note: When UserDefaults sets data, it does not write immediately, but regularly writes the cached data to the local disk based on the timestamp. Therefore, after the set method is called, data may be terminated before being written to the disk application.. If the preceding problem occurs, you can call the synchornize method to forcibly write data.

 

[Defaults synchornize];

3. NSKeyedArchiver

 

If the object is of the NSString, NSDictionary, NSArray, NSData, or NSNumber type, you can use NSKeyedArchiver to archive and restore the object. Not all objects can be archived directly using this method, only objects that comply with the NSCoding protocol can NSCoding Protocol

 

EncodeWithCoder :

This method is called every time an object is archived. Generally, this method specifies how to archive each instance variable in the object. You can use encodeObject: forKey: Method to archive instance variables.

InitWithCoder:
This method is called every time an object is restored (decoded) from a file. The decodeObject: forKey method is used to decode the instance variable of the object.

Archive NSArray
Encoding:
[NSKeyedArchiver archiveRootObject:arraytoFile:path]

Decoding:

 

NSArray *array = [NSKeyedUnarchiver unarchiveObjectWithFile:path];

 

Archive Person object

Person:

 

@interface Person : NSObject
   
    @property (nonatomic, copy) NSString *name;@property (nonatomic, assign) int age;@property (nonatomic, assign) float height;@end
   

 

 

@implementation Person- (void)encodeWithCoder:(NSCoder *)encoder {    [encoder encodeObject:self.name forKey:@"name"];    [encoder encodeInt:self.age forKey:@"age"];    [encoder encodeFloat:self.height forKey:@"height"];}- (id)initWithCoder:(NSCoder *)decoder {    self.name = [decoder decodeObjectForKey:@"name"];    self.age = [decoder decodeIntForKey:@"age"];    self.height = [decoder decodeFloatForKey:@"height"];    return self;}- (void)dealloc {    [super dealloc];    [_name release];}@end
Archive
Person *person = [[[Person alloc] init] autorelease];person.name = @"name";person.age = 30;person.height = 1.80f;[NSKeyedArchiver archiveRootObject:person toFile:path];
Decoding
Person *person = [NSKeyedUnarchiver unarchiveObjectWithFile:path];

Note:

 

If the parent class also complies with the NSCoding protocol, note that the following should be added to the encodeWithCoder: method:

[Super encodeWithCode: encode];

Ensure that the inherited instance variables can also be encoded, that is, they can also be archived.

Add the following sentence to the initWithCoder: method:

Self = [super initWithCoder: decoder];

Make sure that the inherited instance variables can also be decoded and restored.


 

 

 

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.