Introduction to four data persistence methods commonly used in iOS

Source: Internet
Author: User

There are basically four ways to persist data in iOS: Attribute list, Object archive, SQLite3, and core data


1. List of properties
Main classes involved: Nsuserdefaults, General [Nsuserdefaults Standarduserdefaults] it's enough.

@interface User:nsobject <NSCoding>*name; @end

How to use
1). Separate access

// Save [[Nsuserdefaults standarduserdefaults] Setinteger:userid forkey:@ "UserID"]; [[Nsuserdefaults Standarduserdefaults] setobject:name forkey:@ "name"];
// Take Nsinteger uId = [[[Nsuserdefaults Standarduserdefaults] integervalueforkey:@ "UserID"]; NSString* name = [[Nsuserdefaults standarduserdefaults] stringforkey:@ "name"];

2). Access by Object

// Save [[Nsuserdefaults standarduserdefaults] setobject:self forkey:@ "user"]; // Take user* u = [[Nsuserdefaults standarduserdefaults] Objectforkey "@" user "];

2. Object archiving
To use object archiving, an object must implement the Nscoding protocol. Most object C objects conform to the Nscoding protocol, or they can implement the Nscoding protocol in a custom object, implementing the Nscoding protocol and implementing two methods:
-(void) Encodewithcoder: (Nscoder *) encoder and-(void) Initwithcoder: (Nscoder *) encoder
At the same time, the proposed object also implements the Nscopying protocol, which allows the replication of objects, to implement the Nscopying protocol must implement-(ID) Copywithzone: (Nszone *) Zone method.

@interfaceUser:nsobject <NSCoding>@property (nonatomic, assign) Nsinteger UserID; @property (nonatomic, copy) NSString*name;@end@implementationUser//The following two methods must be implemented, otherwise the call will be crash- (void) Encodewithcoder: (Nscoder *) Acoder; {//This places the properties that need to be persisted[Acoder encodeobject:[nsnumber NumberWithInteger:self.userID] forkey:@ "UserID"]; [Acoder encodeObject:self.name Forkey:@"name"];}- (ID) Initwithcoder: (Nscoder *) adecoder{if(self =[self init]) {//it must be consistent with the contents of the Encodewithcoder method, otherwise it will not read the dataSelf.userid = [[Adecoder decodeobjectforkey:@"UserID"] Integervalue];self.name= [Adecoder Decodeobjectforkey:@"name"];}returnSelf ;}//How to use+(BOOL) Save {nserror*error =Nil;//determine the storage path, typically a file in the document directorynsstring* FileName =[self getfilename]; NSString* FilePath =[self getfilepath];if(! [[Nsfilemanager Defaultmanager] Createdirectoryatpath:filepath withintermediatedirectories:yes attributes:nil Error :&ERROR]) {NSLog (@ "Failed to create user file directory");returnNO;}return[Nskeyedarchiver archiverootobject:self Tofile:[filename:userid];}@end

3.sqlite3
SQLite is an open-source embedded relational database, which was made in 2000 by D. Richard Hipp released, which reduces the overhead of application management data, SQLite portability is good, easy to use, small, efficient and reliable.
SQLite is embedded in applications that use it, and they share the same process space instead of a single process. Externally, it's not like an RDBMS, but inside the process it's a complete, self-contained database engine. One of the great benefits of an embedded database is that you don't need a network configuration or management within your program. Because the client and the server are running in the same process space. SQLite's database permissions depend only on the file system, without the concept of a user account. SQLite has a database-level lock and no network server. It requires less memory, other overhead, and is suitable for use in embedded devices. All you need to do is to compile it correctly into your program.
The development of SQLite more information, here no longer elaborate. It is only recommended that you do not manipulate the SQLite library directly, but instead use some open source third-party libraries. Like what:
Fmdb:https://github.com/ccgus/fmdb.git
Have done a good package for SQLite.


4.Core Data
Core data is essentially using SQLite to save it, but it doesn't need to write any SQL statements.

To use core data, you need to design individual entities and define their properties and relationships in the data Model Editor in Xcode. Then, by manipulating these objects, the data is persisted in conjunction with core data:

Nsmanagedobjectcontext *context =[Appdelegate Managedobjectcontext]; Nserror*error; NSString*fieldname = [NSString stringWithFormat:@"test%d", I]; Uitextfield*thefield =[self valueforkey:fieldname]; Nsfetchrequest*request =[[Nsfetchrequest alloc] init];//Create a description statement that requires a line object. is similar to restricting the Line table in the database. Nsentitydescription *entitydescription = [nsentitydescription entityforname:@" Line"Inmanagedobjectcontext:context]; [Request Setentity:entitydescription];//Create a restrictive statement, similar to where linenum in an SQL statement = iNspredicate *pred = [Nspredicate predicatewithformat:@"(LineNum =%d)", I]; [Request setpredicate:pred]; Nsmanagedobject*theline =Nil; Nsarray*objects = [Context executefetchrequest:request error:&ERROR];if(Objects = =Nil) {NSLog (@ "There is an error!");//Do whatever error handling is appropriate}if([Objects Count] >0){//if an object that meets the criteria exists, remove theTheline = [Objects Objectatindex:0];}Else{//If it does not exist, a new one is inserted.Theline = [Nsentitydescription insertnewobjectforentityforname:@" Line"Inmanagedobjectcontext:context];  [Theline setvalue:[nsnumber numberwithint:i] forkey:@ "LineNum"]; //set the property of this object, CoreData will automatically write it to SQLite[Theline setValue:theField.text Forkey:@"Linetext"]; [Request release];}}

The following is the process of fetching data:

Core_data_persistenceappdelegate *appdelegate = [[UIApplication sharedapplication]Delegate]; Nsmanagedobjectcontext*context =[Appdelegate Managedobjectcontext]; Nsentitydescription*entitydescription = [Nsentitydescription entityforname:@" Line"Inmanagedobjectcontext:context]; Nsfetchrequest*request =[[Nsfetchrequest alloc] init]; [Request Setentity:entitydescription]; Nserror*error; Nsarray*objects = [Context executefetchrequest:request error:&ERROR];if(Objects = =Nil) {NSLog (@ "There is an error!");//Do whatever error handling is appropriate}//Each object is represented in CoreData as a Nsmanagedobject object (similar to each row in a database table) whose properties are obtained by key/value for(Nsmanagedobject *oneobjectinchobjects) {NSNumber*linenum = [Oneobject valueforkey:@"LineNum"]; NSString*linetext = [Oneobject valueforkey:@"Linetext"];} [Request release];

Introduction to four data persistence methods commonly used in iOS

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.