Four data retention Methods

Source: Internet
Author: User
Four Data Storage Methods for iOS (15:04:53) reprinted by ghost during iOS development, no matter what application it is, it will encounter data storage problems. Saving data locally makes the program run more smoothly without the annoying chrysanthemum shape, which makes the user experience better. What's next? Data Storage Method: 1. nskeyedarchiver: saves data in the form of archive. The data object must comply with the nscoding protocol, and the class corresponding to the object must be provided to encodewithcoder: And initwithcoder: method. Before? One method tells the system how to encode the object, and then? One method is to tell the system how to decode the object. For example, archive and save a possession object. Define possession: @ interface possession: nsobject {// follow nscoding nsstring * Name; // type to be archived} @ implementation possession-(void) encodewithcoder :( nscoder *) ecoder {[ecoder encodeobject: Name forkey: @ "name"];}-(void) initwithcoder :( nscoder *) adecoder {name = [adecoder decodeobjectforkey: @ "name"] retain];} archive operation: If you archive and save the possession object allpossession, you only need the nscoder subclass nskeyedarchiver method archiverootobject: tofile. Nsstring * Path = [self possessionarchivepath]; [nskeyedarchiver archiverootobject: allpossessions tofile: path] unzipping operation: Call the nscoder subclass authorization method: tofile: allpossessions =: path] retain]; disadvantage: archive to save data? One-time archive storage and? Decompress the package once. Therefore, you can only target a small amount of data, and the data operations are clumsy? In a small part, you still need to decompress the entire data or archive the entire data. 2. nsuserdefaults: used to save application settings and attributes and user-saved data. After the user opens the program again or starts the system, the data is still stored. The data types that nsuserdefaults can store include nsdata, nsstring, nsnumber, nsdate, nsarray, and nsdictionary. To store other types, you must convert them to the previous type before using nsuserdefaults. The specific implementation is: save data: nsuserdefaults * defaults = [nsuserdefaults standarduserdefaults]; nsstring * name [email protected] "default string"; [defaults setobject: firstname forkey: @ "name"]; // obtain the uiimage instance uiimage * image = [[uiimage alloc] initwithcontentsoffile: @ "photo.jpg"]; nsdata * imagedata = uiimagejpegrepresentation (image, 100 ); // convert the uiimage object to nsdata [defaults synchronize]; // use the synchronize method to persistently read the data to the standarduserdefaults database. Data Retrieval: nsuserdefaults * defaults = [nsuserdefaults standarduserdefaults]; nsstring * name = [defaults objectforkey: @ "name"]; // retrieve namensdata * imagedata = [defaults dataforkey: @ "image"]; uiimage * image = [uiimage imagewithdata: imagedata]; // convert nsdata to uiimage3. write mode: Permanently saved to the disk. The specific method is: Number? Step 1: Obtain the path where the file is to be saved: nsarray * documentpaths = nssearchpathfordirectoriesindomains (nsdocumentdirectory, nsuserdomainmask, yes); // use the C function nssearchpathfordirectoriesindomains to obtain the full path. This function has three parameters: Directory type, he domain mask, and Boolean value. Where the Boolean value indicates whether to pass ?~ Extension path. And number? A parameter is unchanged, that is, nssearchpathdirectory. In iOS, the last two parameters remain unchanged, that is, nsuserdomainmask and yes. Nsstring * ourdocumentpath = [documentpaths objectatindex: 0]; and? One way is to use the nshomedirectory function to obtain the sandbox path. The specific usage is nsstring * sandboxpath = nshomedirectory (); // once you have the full sandbox path, you can create a path from it, however, you cannot write files or create directories on the current file layer of sandbox. Instead, you should create a directory on this basis? A new writable directory, such as documents, library, or temp. Nsstring * documentpath = [sandboxpathstringbyappendingpathcomponent: @ "events"]; // Add events to the sandbox path! The difference between the two is that using nssearchpathfordirectoriesindomains is safer than adding a document after nshomedirectory. This file category may change in the system to be sent in the future. Step 2: generate the file in this path: nsstring * filename = [documentdirectory stringbyappendingpathcomponent: Filename]; // filename is the name of the file to be saved. Step 3: write data to the file: [data writetofile: Filename atomically: Yes]; // write nsdata-type object data to a file named filename. Finally, read the data from the file: nsdata DATA = [nsdata datawithcontentsoffile: filename options: 0 error: NULL]; // read data from filename 4. SQLite: uses the SQLite database to store data. SQLite? In iOS, compared with the previous three storage methods, is a small database relatively complex? Some. Or? Step by step! Number? Step 1: add the library and header file related to SQLite: Find link binary Library (ies) in build phases of the project file and add libsqlite3.0.dylib (the difference between libsqlite3.dylib and libsqlite3.dylib is unknown for the moment, the two should be similar); Add the header file # import "/usr/include/sqlite3.h" to the project file or the source file. Step 2: Start Using SQLite: note before use: if no table is added to the database, the database is not created and no files are generated on the hard disk. If the database already exists, the database is opened. Nsarray * documentspaths = require (nsdocumentdirectory, nsuserdomainmask, yes); nsstring * databasefilepath = [[documentspaths objectatindex: 0] stringbyappendingpathcomponent: @ "mydb"]; // you are familiar with the above two sentences! // Open the database if (sqlite3_open ([databasefilepath utf8string], & database) = sqlite_ OK) {nslog (@ "SQLite dadabase is opened. ");} else {return;} // if the database is not opened successfully, the system returns the result. If no table exists in the database, the system creates the table! Char * error; const char * createsql = "create table (ID integer primary key autoincrement, Name text)"; if (sqlite3_exec (Database, createsql, null, null, & error) = sqlite_ OK) {nslog (@ "create table is OK. ");} else {sqlite3_free (error); // clear the error string after each use and provide it? After a table is created using}, the insert record starts: const char * insertsql = "insert into a person (name) values ('gg ')"; if (sqlite3_exec (database, insertsql, null, null, & error) = sqlite_ OK) {nslog (@ "insert operation is OK. ");} else {nslog (@" error: % s ", error); nslog (@" error: % s ", error); sqlite3_free (error ); // clear the error string after each use and provide it? Under one use? One-step query record: const char * selectsql = "select ID, name from a person"; sqlite3_stmt * Statement; If (sqlite3_prepare_v2 (Database, selectsql,-1, & statement, nil) = sqlite_ OK) {nslog (@ "Select Operation is OK. ");} else {sqlite3_free (error);} while (sqlite3_step (statement) = sqlite_row) {int _ id = sqlite3_column_int (statement, 0 ); nsstring * name = (char *) sqlite3_column_text (statement, 1); nslog (@ "row> ID % I, name % s", _ id, Name);} sqlite3_finalize (statement); finally, close the database: sqlite3_close (database); Note: When writing data to the database, the string can be char, but the char type is retrieved from the database, garbled characters appear when the char type represents Chinese characters. This is because the database uses ASCII encoding by default. Therefore, to retrieve Chinese characters from the database correctly, nsstring must be used to receive the strings retrieved from the database.

 

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.