Data access in sandbox and sandbox Data Access

Source: Internet
Author: User

Data access in sandbox and sandbox Data Access
I. Sandbox 1. Common Methods for storing iOS app data

XML property list (plist) Archiving

Preference)

NSKeyedArchiver archive (NSCoding)

SQLite3

CoreData

2. Apply sandbox

Each iOS app has its own application sandbox (the application sandbox is the file system directory), which is isolated from other file systems. Other applications cannot access the content in the sandbox.

The root path of the simulator application sandbox is: (apple is the user name, 6.0 is the Simulator version)

/Users/apple/Library/ApplicationSupport/iPhone Simulator/6.0/Applications

3. Apply the sandbox Structure
  • Documents: stores the persistent data generated during application running. This directory is backed up when the iTunes synchronization device is used. For example, a game application can save a game archive to this directory.
  • Tmp: Save the temporary data required for running the application. After using the temporary data, delete the corresponding files from this directory. 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.
  • Library/Caches: stores the persistent data generated during application running. This directory is not backed up when the iTunes device is synchronized. Non-important data that generally has a large storage space and does not need to be backed up
  • Library/Preference: saves all the Preference Settings of the application. The iOS Settings application searches for the application Settings in this directory. This directory is backed up when the iTunes synchronization device is running.
4. common methods for obtaining the sandbox directory

Sandbox root directory: NSString * home = NSHomeDirectory ();

Documents: (two methods)

  • We recommend that you use the sandbox root directory to concatenate the "statements" string, because the new version of the operating system may modify the directory name.
1 NSString *home = NSHomeDirectory();2 NSString *documents = [home stringByAppendingPathComponent:@"Documents"];
  • Use the NSSearchPathForDirectoriesInDomains Function
1 // NSUserDomainMask indicates finding from the user folder 2 // YES indicates the Tilde "~" in the expanded path 3 NSArray * array = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, NO); 4 // in iOS, only one directory matches the input parameter, therefore, this set contains only one element 5 NSString * documents = [array objectAtIndex: 0];

 

Tmp: NSString * tmp = NSTemporaryDirectory ();

Library/Caches: (two methods similar to those provided by Documents)

  • Concatenate a "Caches" string using the sandbox root directory
  • Use the NSSearchPathForDirectoriesInDomains function (change the 2nd parameters of the function to NSCachesDirectory)

Library/Preference: Use the NSUserDefaults class to access the setting information in this directory.

Ii. Archiving and recovery (Decoding) 1. attribute list

The property list is an XML file named 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.

2. Archive NSDictionary

Archive an NSDictionary object to a plist attribute list:

1 // encapsulate data into a dictionary 2 NSMutableDictionary * dict = [NSMutableDictionary dictionary]; 3 [dict setObject: @ "hen" forKey: @ "name"]; 4 [dict setObject: @ "15013141314" forKey: @ "phone"]; 5 [dict setObject: @ "27" forKey: @ "age"]; 6 7 // persists the dictionary to Documents/stu. in the plist file, 8 [dict writeToFile: path atomically: YES];
3. Restore NSDictionary

Read the attribute list and restore the NSDictionary object:

1 // read Documents/stu. plist content, instantiate NSDictionary2 NSDictionary * dict = [NSDictionary dictionaryWithContentsOfFile: path]; 3 NSLog (@ "name: % @", [dict objectForKey: @ "name"]); 4 NSLog (@ "phone: % @", [dict objectForKey: @ "phone"]); 5 NSLog (@ "age: % @", [dict objectForKey: @ "age"]);
4. preference settings

Many iOS apps support preference settings, such as saving user names, passwords, and font sizes. iOS provides a standard solution to add preference settings to apps.

Each application has an NSUserDefaults instance to access preference settings. For example, save the username, font size, and whether to log on automatically.

1 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];2 [defaultssetObject:@"zhangsan" forKey:@"username"];3 [defaultssetFloat:18.0f forKey:@"text_size"];4 [defaultssetBool:YES forKey:@"auto_login"];

Read last saved settings

1 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];2 NSString *username = [defaults stringForKey:@"username"];3 floattextSize = [defaults floatForKey:@"text_size"];4 BOOLautoLogin = [defaults boolForKey:@"auto_login"];

Note: When UserDefaults is used to set data, the cached data is not written immediately, but regularly written to the local disk according to the timestamp. Therefore, after the set method is called, data may be terminated without being written to the disk application. If the preceding problem occurs, you can call the synchornize method to forcibly write data.

1 [defaults synchornize];
5. NSKeyedArchiver

If the object is of the NSString, NSDictionary, NSArray, NSData, or NSNumber type, you can use NSKeyedArchiver for archiving and restoration.

Not all objects can be archived directly using this method. Only objects that comply with the NSCoding protocol can be archived.

The NSCoding protocol has two methods:

  • 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 the object is restored (decoded) from the file. The decodeObject: forKey method is used to decode the instance variable of the object.
6. NSKeyedArchiver-Archive
1 // archive an NSArray object to Documents/array. archive2 NSArray * array = [NSArray arrayWithObjects: @ "a", @ "B", nil]; 3 [NSKeyedArchiverarchiveRootObject: array toFile: path];

Restore (decode) NSArray object

NSArray *array = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
7. Archiving example

Person. h

1 @interfacePerson : NSObject<NSCoding>2 @property(nonatomic, copy) NSString *name;3 @property(nonatomic, assign) int age;4 @property(nonatomic, assign) float height;5 @end

Person. m

1 @ implementation: Person 2 // declare the attribute to be stored in this method 3-(void) encodeWithCoder :( NSCoder *) encoder {4 [super encodeWithCoder: encoder]; 5 [encoder encodeObject: self. name forKey: @ "name"]; 6 [encoder encodeInt: self. age forKey: @ "age"]; 7 [encoder encodeFloat: self. height forKey: @ "height"]; 8} 9 10 // constructor. When initializing an object, this method is called 11-(id) initWithCoder :( NSCoder *) decoder {12 if (self = [super initWithCoder: decoder]) {13 self. name = [decoder decodeObjectForKey: @ "name"]; 14 self. age = [decoder decodeIntForKey: @ "age"]; 15 self. height = [decoder decodeFloatForKey: @ "height"]; 16} 17 return self; 18} 19 @ end

 

Archive

1 Person *person = [[Person alloc] init];2 person.name= @"zhangsan";3 person.age= 18;4 person.height= 1.73f;5 6 [NSKeyedArchiverarchiveRootObject:person toFile:path];

Restore

1 Person *person = [NSKeyedUnarchiver unarchiveObjectWithFile:path];

If the parent class also complies with the NSCoding protocol, note the following:

The [super encodeWithCode: encode] should be added to the encodeWithCoder: method to ensure that the inherited instance variables can also be encoded, that is, they can also be archived.

Add self = [super initWithCoder: decoder] To the initWithCoder: method to ensure 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.