Introduction to four data persistence methods commonly used in iOS

Source: Internet
Author: User

Introduction to four data persistence methods commonly used in iOS

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>
@property (nonatomic, assign) Nsinteger UserID;
@property (nonatomic, copy) NSString *name;
@end


1). Separate access
//save

[[nsuserdefaults Standarduserdefaults] setobject:name forKey:@ "name"];
//fetch
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, the nscoding protocol must be implemented for the image. Most object C objects conform to the Nscoding protocol, or implement the Nscoding protocol in custom objects, 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.
@interface User:nsobject <NSCoding>
@property (nonatomic, assign) Nsinteger UserID;
@property (nonatomic, copy) NSString *name;
@end

@implementation User
///The following two methods must be implemented, or in the call will be crash
-(void) Encodewithcoder: (Nscoder *) Acoder;
{
//Place 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 data
Self.userid = [[Adecoder decodeobjectforkey:@ "UserID"] integervalue];
self.name = [adecoder decodeobjectforkey:@ "name"];
}
return self;
}

+ (BOOL) Save {
nserror *error = nil;
//determines the storage path, typically a file in the document directory

nsstring* filePath = [self getfilepath];
if (![ [Nsfilemanager Defaultmanager] Createdirectoryatpath:filepath withintermediatedirectories:yes attributes:nil Error: &error] {
nslog (@ "Failed to create user file directory");
return NO;
"
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,

It reduces the overhead of application management data , SQLite portability is good, easy to use, very 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 DESCRIPTION statement, demand 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 = i
nspredicate *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 the qualifying object is present, remove
theline = [objects objectatindex:0];
}
else {//If it does not exist, insert a new one.
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 as a Nsmanagedobject object in CoreData (similar to each row in a database table) whose properties are obtained by key/value
For (Nsmanagedobject *oneobject in objects)
{
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.