Data storage for iOS development

Source: Internet
Author: User
Tags xml attribute

Common ways for iOS app data storage

    • XML attribute list (plist) archive
    • Preference (preference setting)
    • Nskeyedarchiver Archive (nscoding)
    • SQLite3
    • Core Data

Apply Sandbox

    • Each iOS app has its own app sandbox (the app sandbox is the app's folder) and is isolated from other file systems. Apps must stay in their sandbox, other apps can't access the sandbox
    • Apply the sandbox's file system directory as shown (assuming that the app's name is called layer)

The root path of the emulator app sandbox is: (Apple is the user name, 6.0 is the emulator version)/users/apple/library/application Support/iphone simulator/6.0/applications

Application Sandbox structure Analysis

    • Application Package: (layer in) contains all the resource files and executable files
    • Documents: Saves data that needs to be persisted when the app runs, and it backs up the directory when itunes synchronizes the device. For example, a game app can save a game archive in that directory
    • TMP: Saves the temporary data required to run the app, and then deletes the corresponding file from the directory when it is finished. When the app is not running, the system may also purge files in that directory. itunes does not back up this directory when syncing the device
    • Library/caches: Saves data that needs to be persisted when the app runs, and itunes syncs the device without backing up the directory. Non-critical data with large storage volumes and no backup required
    • Library/preference: Save all your app's preferences, and the iOS settings (settings) app will find the app's settings in that directory. This directory is backed up when itunes syncs the device

Common ways to get the sandboxed catalog applied 

1. Sandbox root directory:

NSString *home = Nshomedirectory ()

2.Documents Catalog: (2 ways) 1. Stitching the "Documents" string with the sandbox root
NSString *home =*documents = [Home stringbyappendingpathcomponent:@documents] ]; // not recommended because a new version of the operating system may modify the directory name

2. Using the Nssearchpathfordirectoriesindomains function

// Nsuserdomainmask representative from the user folder to find // YES represents the wavy character "~" in the expanded path Nsarray *array =  nssearchpathfordirectoriesindomains (nsdocumentdirectory, Nsuserdomainmask, NO); // in iOS, only one directory matches the parameters passed in, so there is only one element in the collection NSString *documents = [array Objectatindex:0];

3. tmp: Directory

NSString *tmp = Nstemporarydirectory ();

4. Library/caches Directory (2 methods similar to documents)

1. Use the sandbox root to stitch the "Caches" string 2. Use the Nssearchpathfordirectoriesindomains function (change the function's 2nd parameter to: nscachesdirectory) 5. Library/preference Directory Access to settings information in this directory through the Nsuserdefaults class Property list plist file
    • The attribute list is an XML-formatted file that expands to the name plist
    • If the object is NSString, Nsdictionary, Nsarray, NSData, NSNumber, and so on, you can use the writetofile:atomically: method to write the object directly to the property list file

Attribute List-Archive nsdictionary

Archive a Nsdictionary object to a list of plist properties
//encapsulate data into a dictionarynsmutabledictionary*dict =[Nsmutabledictionary dictionary]; [Dict setobject:@"Hens"Forkey:@"name"]; [Dict setobject:@"15013141314"Forkey:@"Phone"]; [Dict setobject:@" -"Forkey:@" Age"];//persisting a dictionary to a documents/stu.plist file[Dict Writetofile:path atomically:yes];

Property List-Restore Nsdictionary

Read the property list and restore the Nsdictionary object
//reads the contents of the documents/stu.plist, instantiates the nsdictionaryNsdictionary *dict =[Nsdictionary Dictionarywithcontentsoffile:path]; NSLog (@"name:%@", [Dict Objectforkey:@"name"]); NSLog (@"phone:%@", [Dict Objectforkey:@"Phone"]); NSLog (@"age:%@", [Dict Objectforkey:@" Age"]);

Preference settings

Many iOS apps support preferences such as saving usernames, passwords, font size, and so on, and iOS offers a standard set of solutions to add preferences to your app. Each app has a Nsuserdefaults instance that accesses preferences. For example, save the user name, font size, and whether to log in automatically.
Nsuserdefaults *defaults = [Nsuserdefaults standarduserdefaults];[ Defaults setobject:@ "test" forkey:@ "username"]; [Defaults setfloat: 18.0f forkey:@ "text_size"]; [Defaults setbool:yes forkey: @" Auto_login "];

1. Read the last saved settings

Nsuserdefaults *defaults =*username = [Defaults stringforkey:@ "username"]; float textSize = [Defaults floatforkey:@ "text_size"= [defaults Boolforkey:@ "auto_login"];

   Note: When setting the data, Userdefaults does not write immediately, but instead writes the cached data to the local disk according to the timestamp. So after calling the set method, it is possible that the data has not yet been written to the disk application to terminate. The above problem can be forced by calling the Synchornize method to write
[Defaults synchornize];

Nskeyedarchiver

If the object is NSString, Nsdictionary, Nsarray, NSData, NSNumber and other types, you can archive and restore directly with Nskeyedarchiver. Not all objects can be archived directly in this way, only objects that adhere to the Nscoding protocol. There are 2 ways to nscoding a protocol:
Encodewithcoder: // This method is called every time the object is archived. In this method, you typically specify how to archive each instance variable in an object, and you can use the Encodeobject:forkey: method to archive instance variables
Initwithcoder: // This method is called every time the object is recovered (decoded) from the file. In this method, you typically specify how to decode the data in a file as an instance variable of an object, and you can use the Decodeobject:forkey method to decode the instance variable

nskeyedarchiver-Archive Nsarray

    • Archive a Nsarray object to Documents/array.archive
Nsarray *array = [Nsarray arraywithobjects:@ "a", @ "B", nil];[ Nskeyedarchiver Archiverootobject:array Tofile:path];
    • Archive successful

    • Recovering (decoding) Nsarray objects
Nsarray *array = [Nskeyedunarchiver Unarchiveobjectwithfile:path];

nskeyedarchiver-Archive Person Object (Person.h)

Person.h
@interface person:nsobject<nscoding>*int float Height; @end
Pserson.m
@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"]; returnSelf ;}- (void) Dealloc {[Super Dealloc]; [_name release];}@end

nskeyedarchiver-Archive person Objects (encoding and decoding)

1.L Archive (encoded)
Person *person =@ "MJ"1.83f; [ Nskeyedarchiver Archiverootobject:person Tofile:path];
2. Restore (decode)
Person *person = [Nskeyedunarchiver Unarchiveobjectwithfile:path];

Note for nskeyedarchiver-archived objects

If the parent class also adheres to the Nscoding protocol, note that you should add a sentence in the Encodewithcoder: method
[Super Encodewithcode:encode];

Ensure that inherited instance variables can also be encoded, which can also be archived. Should add a sentence to the Initwithcoder: method

self = [super Initwithcoder:decoder];

Ensure that inherited instance variables can also be decoded, which can also be restored

NSData

Use the Archiverootobject:tofile: method to write an object directly to a file, but sometimes you might want to write multiple objects to the same file, then use NSData to archive the object. NSData can provide temporary storage for some data for subsequent writing to a file, or for storing the contents of a file read from disk. You can use [Nsmutabledata data] To create variable data spaces. SQLite3 1.sqlite3 is an open-source, embedded relational database with good portability, ease of use, and small memory overhead 2.sqlite3 is untyped, meaning you can save any type of data to any field in any table. For example, the following statement of the creation is legal:
CREATE table T_person (name, age);

However, to ensure readability, it is recommended that you add the field type:

CREATE table T_person (name text, age integer);

3.sqlite3 5 data types commonly used: text, Integer, float, Boolean, blob 4. Using SQLite3 in iOS, you first add the library file Libsqlite3.dylib and import the primary header file 5. Execute a statement of the creation
Char *errormsg;  // used to store error messages Char " CREATE table if not exists T_person (ID integer primary key autoincrement, name text, age integer); " ; int result = sqlite3_exec (db, SQL, NULL, NULL, &ERRORMSG);

Sqlite3_exec () can execute any SQL statements, such as Create tables, update, insert, and delete operations. However, it is generally not necessary to execute a query statement because it does not return the queried data.  Sqlite3_exec () can also execute the statement: ① open transaction: BEGIN TRANSACTION;  ② ROLLBACK TRANSACTION: rollback;  ③ COMMIT TRANSACTION: Commit; 6. Inserting data with placeholders
Char*sql ="INSERT into T_person (name, age) VALUES (?,?);"; sqlite3_stmt*stmt;if(SQLITE3_PREPARE_V2 (DB, SQL,-1, &stmt, NULL) = =SQLITE_OK) {Sqlite3_bind_text (stmt,1,"Hens", -1, NULL); Sqlite3_bind_int (stmt,2, -);}if(Sqlite3_step (stmt)! =Sqlite_done) {NSLog (@"Insert Data Error");} Sqlite3_finalize (stmt);

Code parsing: SQLITE3_PREPARE_V2 () The return value equals SQLITE_OK, stating that the SQL statement is ready for success without a syntax problem Sqlite3_bind_text (): Most of the binding functions have only 3 parameters ① the 1th parameter is Sqlite3 _STMT * Type ② the 2nd parameter refers to the position of the placeholder, the position of the first placeholder is 1, not the 0③ 3rd parameter refers to the value to be bound by the placeholder ④ 4th parameter refers to the length of the data passed in the 3rd parameter, and for the C string, you can pass 1 instead of the length of the string ⑤ The 5th parameter is an optional function callback, which is typically used to complete the memory cleanup work after the statement is executed Sqlite_step (): Execute SQL statement, return Sqlite_done represents successful execution Sqlite_finalize (): Destroy SQLITE3_STMT * Object 7. Querying data
Char*sql ="select Id,name,age from T_person;"; sqlite3_stmt*stmt;if(SQLITE3_PREPARE_V2 (DB, SQL,-1, &stmt, NULL) = =SQLITE_OK) {     while(Sqlite3_step (stmt) = =Sqlite_row) {        int_id = Sqlite3_column_int (stmt,0); Char*_name = (Char*) Sqlite3_column_text (stmt,1); NSString*name =[NSString Stringwithutf8string:_name]; int_age = Sqlite3_column_int (stmt,2); NSLog (@"id=%i, name=%@, age=%i", _id, name, _age); }}sqlite3_finalize (stmt);
Code parsing: Sqlite3_step () returns Sqlite_row represents traversing to a new record sqlite3_column_* () to get the corresponding value for each field, and the 2nd parameter is the index of the field, starting with 0 Core DataThe Core data Framework provides an object-relational mapping (ORM) capability to convert OC objects into data, save them in a SQLite3 database file, and restore data saved in a database to OC objects. There is no need to write any SQL statements during this data operation. Use this feature to add Coredata.framework and import primary header files <CoreData/CoreData.h>

Data storage for iOS development

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.