Four ways to store IOS locally

Source: Internet
Author: User

In the course of iOS development, no matter what application you do, you will encounter the problem of data preservation. Save the data locally, allowing the program to flow more smoothly without a nasty daisy state. Make the user experience better. Here's how to save data:

1. NSKeyedArchiver : The data is stored in the form of an archive that requires adherence to the NSCoding protocol, and the class that corresponds 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, Possession save the object archive.
  definition possession: @interface possession:nsobject{//comply with nscoding protocol NSString *name;//to archive type} @implementation possession-( void) encodewithcoder: (Nscoder *) acoder{[acoder encodeObject:name Span class= "hljs-string" >forkey:@ "name"];} -(void) initwithcoder: (Nscoder *) adecoder{Name=[[aDeCoder Span class= "hljs-string" >decodeobjectforkey:@ "name"] retain];}     
    • Archive operations: If you Possession save an object allPossession archive, you only need NSCoder NSKeyedArchiver the method of the subclass archiveRootObject:toFile: .

    • 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.
    NSUserDefaultsThe types of data that can be stored 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:Nsuserdefaults *defaults =[Nsuserdefaults Standarduserdefaults];NSString *name [email protected] "Default string "; [Defaults setobject:name Forkey:@ "name"];Get UIImage instancesUIImage *image=[[UIImage Alloc]initwithcontentsoffile:@ "Photo.jpg"];NSData *imagedata =uiimagejpegrepresentation (image, 100); @ "image"]; [ Defaults synchronize]; //using synchronize method to persist data to standarduserdefaults database read data: nsuserdefaults standarduserdefaults]; NSString *name = [Defaults objectforkey:@ "name"]; Remove Namensdata *imagedata = [Defaults dataforkey:@ "image according to key value "]; uiimage *image = [uiimage Imagewithdata:imagedata];//nsdata convert to UIImage           

3.Write write mode: 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);Use the C function 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 you need to extend the path through the? ~. And the first parameter is constant, that is, theNssearchpathdirectory. In iOS, the latter two parameters are the same:nsuserdomainmask  and  YES. nsstring *ourdocumentpath =[documentpaths objectatindex:0]; What's more? One 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 can not write   file on the sandbox of this file can not create Build the catalog, and should be created on this basis? A new writable directory, such as Documents,library or temp.  nsstring *documentpath = [Sandboxpathstringbyappendingpathcomponent:@ "Documents"] ; //add documents to the sandbox path, the original   because of the previous analysis! The difference between the two is: use nshomedirectory. Because the file   record may change on the system that is sent in the future. 
    • Step two: Generate files under this path:
stringByAppendingPathComponent:fileName];//fileName就是保存文件的文件 名第三步:往文件中写入数据:[data writeToFile:FileName atomically:YES];//将NSData类型对象data写入文件,文件名为FileName最后:从文件中读出数据:NSData data=[NSData dataWithContentsOfFile:FileName options:0 error:NULL];//从FileName中读取出数据

4.SQLite: Use SQLite database to store data. SQLite as a small and medium-sized database, in the application of iOS, the previous three ways to save compared to a relatively more complex. It's a step-by-step!

    • The first step: you need to add SQLite-related libraries and header files: in the project file

      Binary Library(ies),添加libsqlite3.0.dylib(libsqlite3.dylib与前者的区别暂时不知,两者应该差不多);在项目文件中头文件或者源文件中添加头文件 #import "/usr/include/sqlite3.h"
  • Step two: Start using SQLite: note: If you do not add any tables to the database, this database is not established, will not generate any files on the hard disk, if the database already exists, it will open the database.
 nsarray *documentspaths= nssearchpathfordirectoriesindomains ( NSDocumentDirectory, nsuserdomainmask, YES); nsstring *databasefilepath=[[documentspaths objectatindex:0] Stringbyappendingpathcomponent:@ "MyDB"];        
 //the above two lines are already familiar.!if (Sqlite3_open ([Databasefilepath utf8string], &database) ==SQLITE_OK) { Span class= "hljs-built_in" >nslog (@ "SQLite dadabase is opened."); else{return;} //open unsuccessful returns          
  • When 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 {sqlite3_free(error);//每次使用完毕清空error字符串,提供给下?一次使用 }
  • After 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);NSLog(@"error: %s",error);sqlite3_free(error);//每次使用完毕清空error字符串,提供给下一次使用 }
  • Next step, query record:

ConstChar *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); char*) sqlite3_column_text (statement, 1); Span class= "hljs-built_in" >nslog (@ "Row>>id%i, Name%s", _ id,name);} Sqlite3_finalize (statement);              
    • Finally, close the database:
sqlite3_close(database);
  • Note: When writing to a database, the string can be taken in a char way, and the type is fetched from the database and char garbled when the char type has a representation of the Chinese character. This is because the database uses ascII encoding by default. Therefore, in order to correctly remove the Chinese from the database, it is necessary NSString to receive the string extracted from the database.

Four ways to store IOS locally

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.