The following 4 types of data storage are commonly used in iOS:
1 , nskeyedachiever//serialization of stored objects 2 NSData, NSString, NSNumber, NSDate, Nsarray, nsdictionary //Storage to the library under the sandbox/preferences/ 3, writetofile:atomically://directly write file way: NSString, Nsarray, Nsdictionary, NSData, NSNumber, stored in a property list file (*.plist file). the document folder
4, the use of database storage SQLite3, coredata//other third-party packaging library like Fmdb, Apple's official iOS5 after the introduction of the Integrated database CoreData (object-oriented than the native database faster, more features)
Here's how data is saved:
Each iOS app has its own app sandbox (the app sandbox is the file system directory) 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
Document: 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
Temp: 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
1.NSKeyedArchiver: Save the data in the form of an archive that requires adherence to the Nscoding protocol, and that the class corresponding to the object must provide Encodewithcoder: and Initwithcoder: Methods. The previous method tells the system how to encode the object, and the latter method tells the system how to decode the object. For example, save the Possession object archive.
//define possession:@interfacepossession:nsobject<nscoding>{//compliance with nscoding protocolNSString*name;//Pending Archive Type}@implementationPossession-(void) Encodewithcoder: (Nscoder *) acoder{[Acoder encodeobject:name forkey:@"name"];} -(void) Initwithcoder: (Nscoder *) adecoder{name=[[adecoder Decodeobjectforkey:@"name"] retain];}
Archive operations:
If you save the possession object Allpossession archive, you only need to nscoder the method Archiverootobject:tofile of the subclass Nskeyedarchiver: Yes.
NSString *path = [self possessionarchivepath];[ Nskeyedarchiver archiverootobject:allpossessions Tofile:path]
Decompression operation:
Also call the method of Nscoder subclass Nskeyedarchiver Unarchiverootobject:tofile: You can
Allpossessions = [[Nskeyedunarchiver Unarchiveobjectwithfile:path] retain];
Cons: Archive the form to save data, only one-time archive save and one-time decompression. So only a small amount of data, and the data operation is clumsy, that is, if you want to change a small part of the data, still need to extract the entire data or archive the entire data.
2.NSUserDefaults: Used to save application settings and properties, user-saved data. The data still exists after the user opens the program again or after powering it on. The types of data that Nsuserdefaults can store include: NSData, NSString, NSNumber, NSDate, Nsarray, Nsdictionary. If you want to store other types, you need to convert to the previous type to use nsuserdefaults storage. The specific implementation is:
Save data:
Library/preferences stored under sandbox
store tags in the form of plist files
Nsuserdefaults *defaults =[Nsuserdefaults Standarduserdefaults]; NSString*name [email protected] "default string"; [Defaults setobject:firstname forkey:@"name"]; //Get UIImage instancesUIImage*image=[[uiimage Alloc]initwithcontentsoffile:@"photo.jpg"]; NSData*imagedata = uiimagejpegrepresentation (image, -);//convert UIImage objects to NSData[Defaults synchronize];//persisting data to the Standarduserdefaults database using the Synchronize method
Read Data :
Nsuserdefaults *defaults =*name = [Defaults objectforkey:@ "name"]; // remove name based on key value NSData *imagedata = [Defaults dataforkey:@ "image"*image = [UIImage imagewithdata: ImageData]; // NSData conversion to UIImage
3. Write writes: Permanently saved on disk. The specific methods are:
Step one: Get the path that the file is about to save:
Nsarray *documentpaths = Nssearchpathfordirectoriesindomains (nsdocumentdirectory, NSUserDomainMask,YES); using C functions
Nssearchpathfordirectoriesindomains to get the full path of the directory in the sandbox. The function has three parameters, a directory type, a he domain mask, and a Boolean value. Where the Boolean value indicates whether the path needs to be extended through the ~. And the first parameter is constant, which is nssearchpathdirectory. In iOS, the latter two parameters are the same: Nsuserdomainmask and YES.
NSString *ourdocumentpath =[documentpaths Objectatindex:0];
Another way is to use the Nshomedirectory function to get the sandbox path. The specific usage is:
NSString *sandboxpath = nshomedirectory (); // Once You has the full sandbox path, you can create a path from it, but cannot write files on the sandbox file layer and cannot create directories, but should be based on creating a new writable directory, example such as Documents,library or temp. nsstring *documentpath = [Sandboxpath stringbyappendingpathcomponent:@ "Documents "]; // add documents to the sandbox path for specific reasons before you analyze them!
The difference between the two is that using Nssearchpathfordirectoriesindomains is more secure than adding a document behind Nshomedirectory. Because the file directory may change on future systems that are sent.
Step two: Generate files under this path:
NSString *filename=[documentdirectory Stringbyappendingpathcomponent:filename]; // FileName is the file name of the saved files
Step three: Write data to the file:
[Data writetofile:filename Atomically:yes]; // writes the 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 out data from filename
4. SQLite: Use SQLite database to store data. SQLite as a small and medium-sized database, the application of iOS, in front of three ways to save compared to a relatively more complex. It's a step-by-step!
First step: You need to add SQLite related libraries and header files: Under Build phases of the project file, locate the link Binary library (ies), Add Libsqlite3.0.dylib (the difference between Libsqlite3.dylib and the former does not know, the two should be similar); Add a header file to the header file or source file in the project file #import "/usr/include/sqlite3.h"
Step two: Start using SQLite:
Nsarray *documentspaths=nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES); NSString*databasefilepath=[[documentspaths Objectatindex:0] stringByAppendingPathComponent:@"MyDB"];//the above two sentences are already more familiar with it! //Open Databaseif(Sqlite3_open ([Databasefilepath utf8string], &database) = =SQLITE_OK) {NSLog (@"SQLite Dadabase is opened."); }Else{return;}//turn on unsuccessful to returnWhen the database is open, if the database does not have a table, then you start to build the table Oh! 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{NSLog (@"Error:%s", error); Sqlite3_free (error);//empty the error string each time it is used, provided to the next useAfter the build table is complete, insert the record: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); Sqlite3_free (error);//empty the error string each time it is used, provided to the next useNext, Query the records: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{NSLog (@"Error:%s", error); 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 (db); Note: To write to a database, the string can be char, and the char type is removed from the database and garbled when the char type has a representation of the Chinese characters. This is because the database uses ASCII encoding by default. Therefore, in order to correctly remove the Chinese from the database, we need to use NSString to receive the string extracted from the database.
Other third-party encapsulation libraries like Fmdb can be used to simplify database operations (Mac version of QQ is also used)
The next section specifically explains the use of Fmde
IOS-How data is stored (localized)