Common Methods for storing iOS app data

Source: Internet
Author: User

There are five data storage methods in ios program:

XML property list (plist) Archiving

Preference)

NSKeyedArchiver archive (NSCoding)

SQLite3

Core Data


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

Shows the file system directory of the application sandbox (assuming the application name is Layer)



<喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + signature/Signature + signature + cve-vcd4kpha + cve-vcd4kpha + signature + o7ooyc/Signature/LqswcvL + signature/Signature/authorization vcD4KPHA + signature + signature/Signature + signature + tNO4w8S/Signature + Wz/bjDxL/CvM/CtcTOxLz + signature/wrw8L3A + signature + CjwvcD4KPHA + CjxzdHJvbmc + signature + signature/Signature + 3TwvcD4KPHA + signature + hu21_dxl/Signature + signature/Signature + cS/Signature/u01_wvcd4kpha + CjxzdHJvbmc + ybO60Lj5xL/Signature operator =" Documents"];

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

Method 2:

Use the NSSearchPathForDirectoriesInDomains Function

NSUserDomainMask indicates to find it from the user folder

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

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

In iOS, there is only one directory that matches the input parameters, so there is only one element in this set.

NSString * documents = [array objectAtIndex: 0];


2,Library/Caches

Tmp: NSString * tmp =NSTemporaryDirectory();

Library/Caches(Two methods similar to statements)

Concatenate a "Caches" string using the sandbox root directory

Use the NSSearchPathForDirectoriesInDomains function (change the 1st parameters of the function to NSCachesDirectory)


3. Library/Preference

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

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.


4,

Archive an NSDictionary object to a plist attribute list

Encapsulate data into dictionaries

NSMutableDictionary * dict = [NSMutableDictionary dictionary];

[Dict setObject: @ "hen" forKey: @ "name"];

[Dict setObject: @ "15013141314" forKey: @ "phone"];

[Dict setObject: @ "27" forKey: @ "age"];

Persists the dictionary to the Documents/stu. plist file.

[Dict writeToFile: path atomically: YES];

Successfully written to the Documents directory


Read the attribute list and restore the NSDictionary object.

Read the contents of Documents/stu. plist and instantiate NSDictionary.


5,

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

NSUserDefaults* Defaults = [NSUserDefaultsStandardUserDefaults];

[DefaultsSetObject: @ "Itcast" forKey: @ "username"];

[DefaultsSetFloat: 18366f forKey: @ "text_size"];

[DefaultsSetBool: YES forKey: @ "auto_login"];


Read last saved settings

NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];

NSString * username = [defaultsStringForKey: @ "Username"];

Float textSize = [defaultsFloatForKey: @ "Text_size"];

BOOL autoLogin = [defaultsBoolForKey: @ "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.

[Defaults synchornize];


6,

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 an object is restored (decoded) from a file. The decodeObject: forKey method is used to decode the instance variable of the object.


Archive an NSArray object to Documents/array. archive

NSArray * array = [NSArray arrayWithObjects: @ "a", @ "B", nil];

[NSKeyedArchiver archiveRootObject: ArrayToFile: Path];

Restore (decode) NSArray object

NSArray * array = [NSKeyedUnarchiver unarchiveObjectWithFile: Path];


Archive an object to Documents


@ Interface Person: NSObject <NSCoding>

@ Property (nonatomic, copy) NSString * name;

@ Property (nonatomic, assign) int age;

@ Property (nonatomic, assign) float height;

@ End


Implementation Person

-(Void) encodeWithCoder :( NSCoder *) encoder {

[EncoderEncodeObject: Self. name forKey: @ "name"];

[EncoderEncodeInt: Self. age forKey: @ "age"];

[EncoderEncodeFloat: Self. height forKey: @ "height"];

}

-(Id) initWithCoder :( NSCoder *) decoder {

Self. name = [decoderDecodeObjectForKey: @ "Name"];

Self. age = [decoderDecodeIntForKey: @ "Age"];

Self. height = [decoderDecodeFloatForKey: @ "Height"];

Return self;

}

-(Void) dealloc {

[Super dealloc];

[_ Name release];

}

@ End


Archive (encoding)

Person * person = [[[Person alloc] init] autorelease];

Person. name = @ "GL ";

Person. age = 27;

Person. height = 1.83f;

[NSKeyedArchiver archiveRootObject: person toFile: path];

Recovery (Decoding)

Person * person = [NSKeyedUnarchiver unarchiveObjectWithFile: path];


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

Add the following sentence 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.


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.