iOS develops simple and efficient data storage

Source: Internet
Author: User

Learn to Exchange discussions please follow Sina Weibo: Geek James

In the process of iOS development, no matter what the application, you will encounter the problem of data preservation, what method do you use to persist data? This is an issue that will be mentioned in almost every communication or discussion about iOS technology, and everyone's enthusiasm for the issue continues to soar. This paper mainly from the concept of "data storage" the problem of analysis, and combined with their respective characteristics and the application of the scene for a comprehensive analysis.

First, Nsuserdefaults

Nsuserdefaults is designed to store configuration information for devices and applications, and it returns the default, and most commonly used, instance objects through a factory method. This object stores the configuration information of the user in the system, which can be modified by the instance object, or the new configuration items can be created according to their own requirements.
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:

NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];NSString *name [email protected]”default string“;[defaults setObject:firstName forKey:@"name"];  //获得UIImage实例
UIImage *image=[[UIImage alloc]initWithContentsOfFile:@"photo.jpg"100);//UIImage对象转换成NSData//用synchronize方法把数据持久化到standardUserDefaults数据库

Read data:

NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];NSString *name = [defaults objectForKey:@"name"//根据键值取出nameNSData *imageData = [defaults dataForKey:@"image"];UIImage *Image = [UIImage//NSData转换为UIImage
Second, archive, archive

Nskeyedarchiver: in the form of an archive, the data object needs to adhere to the Nscoding protocol, and 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:

@interface Possession:NSObject<NSCoding>{//遵守NSCoding协议       NSString *name;//待归档类型}@implementation Possession-(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:

同样调用NSCoder子类NSKeyedArchiver的方法unarchiveRootObject:toFile: 即可  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.

Third, SQLite

Using SQLite storage to query more data is the most common way in our development, such as app interface data cache, offline cache and so on.
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) and add libsqlite3.0.dylib
(The difference between the Libsqlite3.dylib and the former is not known, 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;}//Open not successful on 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);//each use clears the error string for the next use}

After the build table is complete, insert the record:

constchar *insertSql="insert into a person (name) values(‘gg’)"ifNULLNULL, &error)==SQLITE_OK) {         NSLog(@"insert operation is ok."); }else{       NSLog(@"error: %s",error);       sqlite3_free(error);//每次使用完毕清空error字符串,提供给下一次使用

Next, query the 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{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(database)

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.

Iv. CoreData

Core data is more object-oriented than using the SQLite3 API directly, and the operation process is usually divided into the following steps:

1. Create a Management context

Creation management can be subdivided into: Load model file, specify Datastore path, create a corresponding data type, create a management object below and specify storage.

After these steps, you can get the management object context Nsmanagedobjectcontext, in which all data operations are responsible for this object. At the same time, if the context is created for the first time, Core data automatically creates a storage file (for example, using SQLite3 storage) and creates a corresponding table structure based on the model object. The database and related mapping files that were generated for the first run:

To facilitate later use, the Nsmanagedobjectcontext object can be saved as a singleton or a static property, and the following is the main code for the created Management object context:

-(Nsmanagedobjectcontext *) createdbcontext{nsmanagedobjectcontext *context;//Open the model file with nil parameter open all the model files in the package and merge them into oneNsmanagedobjectmodel *model=[nsmanagedobjectmodel Mergedmodelfrombundles:Nil];//Create parserNspersistentstorecoordinator *storecoordinator=[[nspersistentstorecoordinator Alloc]initWithManagedObjectModel: Model];//Create a database save path    NSString*dir=[nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask,YES) Firstobject];NSLog(@"%@", dir);NSString*path=[dir stringbyappendingpathcomponent:@"Mydatabase.db"];Nsurl*url=[NsurlFileurlwithpath:path];//Add SQLite persistent store to parser    Nserror*error; [Storecoordinator addpersistentstorewithtype:nssqlitestoretype configuration:NilUrl:url options:Nilerror:&error];if(Error) {NSLog(@"Database open failed!" Error:%@ ", error. Localizeddescription); }Else{Context=[[nsmanagedobjectcontext Alloc]init]; Context. Persistentstorecoordinator=storecoordinator;NSLog(@"The database opened successfully!" "); }returnContext;}

2. Querying Data
For a conditional query, it is implemented through a predicate in core data. You first create a request, then set the request criteria, and finally call the context to execute the requested method.

-(void) Adduserwithname: (NSString*) name Screenname: (NSString*) Screenname Profileimageurl: (NSString*) Profileimageurl Mbtype: (NSString*) Mbtype City: (NSString*) city{//Add an objectUser *us= [Nsentitydescription insertnewobjectforentityforname:@"User"Inmanagedobjectcontext: Self. Context]; us. Name=name; us. Screenname=screenname; us. Profileimageurl=profileimageurl; us. Mbtype=mbtype; us. City=city;Nserror*error;//Save Context    if(! [ Self. ContextSave:&error]) {NSLog(@"An error occurred during the add process, error message:%@! ", error. Localizeddescription); }}

If there are multiple conditions, as long as a combination of predicates, then how to query the associated object conditions? Here are two scenarios to introduce:

A. Finding a single object with only one associated object, such as finding a Weibo user named "Binger" (a microblog can only belong to one user), through-

(Nsarray ) Getstatusesbyusername: (NSString ) name{
Nsfetchrequest *request=[nsfetchrequest fetchrequestwithentityname:@ "Status"];
Request.predicate=[nspredicate predicatewithformat:@ "user.name=%@", name];
Nsarray *array=[self.context executefetchrequest:request Error:nil];
return array; The SQL statement generated by}ata will find that the status table and the user table are actually associated with the query (join connection).

B. Find a situation where an object has multiple associated objects, such as a user who has "Watch" in the sending microblogging content and a user nickname "Cortana" (one user has multiple tweets), the predicate can be used to

-(Nsarray ) Getusersbystatustext: (nsstring ) text screenname: (NSString *) screenname{
Nsfetchrequest *request=[nsfetchrequest fetchrequestwithentityname:@ "Status"];
Request.predicate=[nspredicate predicatewithformat:@ "text like 'Watch'", text];
Nsarray *statuses=[self.context executefetchrequest:request Error:nil];

NSPredicate *userPredicate= [NSPredicate predicateWithFormat:@"user.screenName=%@",screenName];NSArray *users= [statuses filteredArrayUsingPredicate:userPredicate];return users;

If you simply look for a user with a "Watch" in your microblog, you can find the corresponding Weibo directly and then get the user by using the Users property of each microblog, without the use of additional predicate filters.

3. Inserting data

Inserting data requires calling the entity Description Object Nsentitydescription returns an entity object, sets the object properties, and finally saves the current context. It is important to note that the Save method of the Management object context must be called at the end of the add, delete, and change operation, otherwise the operation will not execute.

-(void) Adduserwithname: (NSString*) name Screenname: (NSString*) Screenname Profileimageurl: (NSString*) Profileimageurl Mbtype: (NSString*) Mbtype City: (NSString*) city{//Add an objectUser *us= [Nsentitydescription insertnewobjectforentityforname:@"User"Inmanagedobjectcontext: Self. Context]; us. Name=name; us. Screenname=screenname; us. Profileimageurl=profileimageurl; us. Mbtype=mbtype; us. City=city;Nserror*error;//Save Context    if(! [ Self. ContextSave:&error]) {NSLog(@"An error occurred during the add process, error message:%@! ", error. Localizeddescription); }}

4. Delete data

Deleting data can directly invoke the DeleteObject method that manages the object context, removing the save context. Note that you must first query the corresponding object before deleting the data.

-(void)removeUser:(User *)user{    [self.context deleteObject:user];    NSError *error;    if (![self.context save:&error]) {        NSLog(@"删除过程中发生错误,错误信息:%@!",error.localizedDescription);    }}

5. Modify the data

Modifying the data first also takes out the corresponding entity object, and then saves the context by modifying the object's properties.

-(void) Modifyuserwithname: (NSString*) name Screenname: (NSString*) Screenname Profileimageurl: (NSString*) Profileimageurl Mbtype: (NSString*) Mbtype City: (NSString*) city{User *us=[ SelfGetuserbyname:name]; us. Screenname=screenname; us. Profileimageurl=profileimageurl; us. Mbtype=mbtype; us. City=city;Nserror*error;if(! [ Self. ContextSave:&error]) {NSLog(@"error occurred during modification, error message:%@", error. Localizeddescription); }}

Debugging
While core Data (if using SQLite database) operations eventually translates to SQL operations, debugging does not make it easy to manipulate SQL. Especially for beginners, the problem of query error often occurs, if you can see the resulting SQL statement is naturally useful for debugging. In fact, in Xcode support core data debugging, the operation: Product-scheme-edit Add two parameters in scheme-run-arguments (note that the parameter order cannot be wrong):-com.apple.coredata.sqldebug, 1. Then, when you run the program, the SQL statement is printed in the output panel if you manipulate the database.

iOS develops simple and efficient data storage

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.