IOS development database-Overview, ios development overview

Source: Internet
Author: User

IOS development database-Overview, ios development overview

Data storage concepts:

Data structure:

  • Basic objects: NSDictionary, NSArray, and NSSet.
  • Complex objects: relational models, object graphs, and attribute lists.

Storage Method:

  • Memory: the memory storage is temporary and effective during runtime, but the efficiency is high.
  • Flash Memory: Flash memory is a type of persistent storage, but it consumes I/O and has low efficiency.

Archiving: Transfers memory data to flash memory for persistent operations.

Common Data Storage solutions:

  • Attribute list: NSArray, NSDictionary, NSData, NSString, NSNumber, NSDate, etc.

This mechanism is supported for basic data types. NSUserDefaults is also a type of attribute list storage, which is commonly used.

Store configuration information. This mechanism can serialize these objects directly to plist files.

It is more efficient to store a small amount of data.

Simple code:

// NSUserDefaults default NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults]; [userDefaults setObject: @ "skyming" forKey: @ "username"]; [userDefaults setObject: [NSDate date] forKey: @ "date"]; [userDefaults setObject: @ [@ "a1", @ "a2"] forKey: @ "array"]; [userDefaults setInteger: 6174 forKey: @ "code"]; NSLog (@ "userDefaults: % @", [userDefaults dictionaryRepresentation]); NSString * username = [userDefaults objectForKey: @ "username"]; NSDate * date = [userDefaults objectForKey: @ "date"]; NSArray * array = [userDefaults objectForKey: @ "array"]; NSInteger code = [userDefaults integerForKey: @ "code"]; NSLog (@ "username: % @ date: % @ \ n array: % @ code: % d", username, date, array, code ); [userDefaults synchronize]; // NSUserDefaults custom NSUserDefaults * defaults = [[NSUserDefaults alloc] init]; [defaults setPersistentDomain: [NSDictionary dictionaryWithObject: @ "Hello" forKey: @ "World"] forName: @ "com. sensoro. defaultsTest "]; [defaults synchronize]; // array NSArray * paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES); NSString * docPath = [paths objectAtIndex: 0]; NSString * myFile = [docPath stringByAppendingPathComponent: @ "my. list "]; // read the file NSArray * array = [[NSArray alloc] initWithContentsOfFile: myFile]; // if data is modified after the operation, write it to the file [array writeToFile: myFile atomically: YES];

 

  • Object Archiving: a common storage mechanism for custom objects. The object must implement the NSCoding protocol, which is optional for the NSCopying protocol.

Simple code

# Pragma mark-# Implementation of The pragma NSCoding protocol-(void) encodeWithCoder :( NSCoder *) ACO {// encoder [ACO encodeObject: self. username forKey: @ "username"]; [aCoder encodeObject: self. password forKey: @ "password"];}-(id) initWithCoder :( NSCoder *) aDecoder {// decoder if (self = [super init]) {self. username = [aDecoder decodeObjectForKey: @ "username"]; self. password = [aDecoder decodeObjectForKey: @ "password"];} return self ;}# pragma NSCopying protocol implementation-(id) copyWithZone :( NSZone *) zone {DSObj * copy = [[self class] allocWithZone: zone] init]; return copy;} // read NSArray * paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES ); NSString * docPath = [paths objectAtIndex: 0]; NSString * myFile = [docPath stringByAppendingPathComponent: @ "dsObj. list "]; // write the archive file NSMutableData * datawrite = [[NSMutableData alloc] init]; optional * archiver = [[NSKeyedArchiver alloc] handler: datawrite]; [archiver encodeObject: test forKey: @ "data"]; [archiver finishEncoding]; [datawrite writeToFile: myFile atomically: YES]; // read the archived file NSData * data = [[NSMutableData alloc] initWithContentsOfFile: myFile]; optional * unarchiver = [[initalloc] initForReadingWithData: data]; DSObj * testread = [unarchiver decodeObjectForKey: @ "data"]; [unarchiver finishDecoding]; NSLog (@ "DSObjRead: % @", [testread username], [testread password]);

When there are many attributes, you cannot add them one by one. I prefer to use a runtime-based solution:

Objects to be archived only need to be inherited.

Link: https://github.com/skyming/SSObjectBase

 

  • SQLite: used to store data that requires a large amount of queries

The SQLite3 library is preset in the iOS SDK, and developers can build their own SQLite database. SQLite writes data each time

IO consumption is generated, and the data is archived to the corresponding file. The data types that SQLite is good at processing are actually compared with NSUser-

Defaults is similar to the basic type of small data, but the organizational form is different. Developers can use relational

The data warehouse organizes data and uses SQL DML to manage data. In general, formatted text classes in applications

Data can be stored in databases, especially those with conditional query and sorting requirements, such as chat records and Timeline.

. Each database handle is allocated with a cache in the memory to improve query efficiency.

On the other hand, because of the query cache, when a large number of handles or data volumes are generated, the cache is too large, resulting in

Memory waste.

Simple code

//open database- (void)openDataBase{    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);    NSString *docPath = [paths objectAtIndex:0];    NSString *myFile = [docPath stringByAppendingPathComponent:@"data.db"];        if (sqlite3_open([myFile UTF8String], &database)==SQLITE_OK)    {        NSLog(@"open sqlite db ok.");    }    else    {        NSLog( @"can not open sqlite db " );                //close database        sqlite3_close(database);    }}//create table- (void)createTable{    char *errorMsg;    const char *createSql="create table if not exists persons (id integer primary key autoincrement,name text)";        if (sqlite3_exec(database, createSql, NULL, NULL, &errorMsg)==SQLITE_OK)    {        NSLog(@"create ok.");    }    else    {        NSLog( @"can not create table" );        [self ErrorReport:[NSString stringWithFormat:@"%s",createSql]];    }}//insert table- (void)insertTable{    char *errorMsg;        const char *insertSql="insert into persons (name) values ('skyming')";    if (sqlite3_exec(database, insertSql, NULL, NULL, &errorMsg)==SQLITE_OK)    {        NSLog(@"insert ok.");    }    else    {        NSLog( @"can not insert it to table" );        [self ErrorReport:[NSString stringWithFormat:@"%s",insertSql]];    }}//query table- (void)queryTable{    const char *selectSql="select id,name from persons";    sqlite3_stmt *statement;    if (sqlite3_prepare_v2(database, selectSql, -1, &statement, nil)==SQLITE_OK)    {        NSLog(@"select ok.");        while (sqlite3_step(statement)==SQLITE_ROW)//SQLITE_OK SQLITE_ROW        {            int _id=sqlite3_column_int(statement, 0);            NSString *name=[[NSString alloc] initWithCString:(char *)sqlite3_column_text(statement, 1) encoding:NSUTF8StringEncoding];            NSLog(@"row>>id %i, name>> %@",_id,name);        }            }    else    {        //error        [self ErrorReport:[NSString stringWithFormat:@"%s",selectSql]];    }        sqlite3_finalize(statement);}//delete table- (void)deleteTable{    char *errorMsg;    [self openDataBase];        const char *sql = "DELETE FROM persons where id=24";    if (sqlite3_exec(database, sql, NULL, NULL, &errorMsg)==SQLITE_OK)    {        NSLog(@"delete ok.");    }    else    {        NSLog( @"can not delete it" );        [self ErrorReport:[NSString stringWithFormat:@"%s",sql]];    }    }//error- (void)ErrorReport: (NSString *)item{    char *errorMsg;        if (sqlite3_exec(database, [item cStringUsingEncoding:NSUTF8StringEncoding], NULL, NULL, &errorMsg)==SQLITE_OK)    {        NSLog(@"%@ ok.",item);    }    else    {        NSLog(@"error: %s",errorMsg);        sqlite3_free(errorMsg);    }}

 

SQLite is much more complex to use than NSUserDefaults. Therefore, we recommend that you use SQLite

It can be used with an operation control to simplify operations. The SQLight developed by gaosboy is

E operation encapsulation, which encapsulates relatively complex SQLite commands into objects and methods for your reference.

Link: https://github.com/gaosboy/SQLight

Many Github star solutions: FMDB

Link: https://github.com/ccgus/fmdb

  • CoreData, used to plan objects in applications

The official definition is an automated management solution that supports persistence, object graphs, and lifecycles. Strict

In a sense, CoreData is a management solution. Its persistence can be achieved through SQLite, XML, or binary

File storage. As the official definition suggests, CoreData is far more effective than simply storing data.

Model and automate the management of objects in the entire application.

The official document explains the example of the object graph given by CoreData.

As shown in, MyDocument is an object instance with two collections: Employee and

Department, which stores the list of objects. MyDocument, Employee, and Department

The three objects and their relationships are modeled using CoreData and can be persisted using the save method.

. When restoring a model from an archive file, CoreData does not load all the data in the entire model at a time.

Memory, but loads the called object instance into the memory according to the running status. The framework automatically controls this

Process to control memory consumption and avoid waste. In terms of design principles and usage, Core-

Data is complex. Therefore, CoreData is definitely not

Optimal Solution. The use scenario of CoreData is that the entire application uses CoreData planning to set the number of data in the application.

Based on CoreData modeling, the application is fully based on the CoreData architecture. An example code officially provided by Apple,

The structure is relatively simple and can help you get started with CoreData.

Link address:

Http://developer.apple.com/library/ios/#samplecode/Locations/Introduction/Intro.html#//apple_ref/doc/uid/DTS40008406

  • Personalized cache solution customized with basic object types

The NSUserDefaults and SQLite mentioned earlier are suitable for storing basic types of small data, while CoreData is not suitable

To store a single data, how can we store large data such as images? Gaosboy

It is recommended that you implement a storage solution by yourself. First, make it clear that this so-called custom solution applies to Internet applications.

Restrictions on remote data caching are indispensable. Analyze the requirements of cache data based on requirements: by Key

Searching, Fast Reading, Writing does not affect normal operations, does not waste memory, and supports archiving. These are basic requirements.

In addition, you may need to set the number of cache items, including queue cache and cache expiration. Design

The cache solution is not very complex. Kache is a set of cache components developed by the author based on the needs of the development application.

Kache hopes to give you some ideas.

 

As shown in, Kache plays a typical cache role. Application load remote data generation Application Data

The data is cached through Kache at the same time, and the data is directly obtained through Kache upon another request.

The cached object can be NSDictionary, NSArray, NSSet, or NSData that can be directly archived,

Each cached object corresponds to a Key. Cache objects include data and expiration time, which are stored in a single instance in memory

In the dictionary, each object in flash memory is saved as a file. The Key space stores the Key set of the cached object in various order.

Pool is a fixed-size array. When the number reaches the upper limit, the first expired Key will be deleted.

Cache objects are also cleared. The Queue is also an array of fixed sizes. It manages the addition and deletion of keys with FIFO rules.

Each time a new cache object is stored, the expired set in the Key space is automatically checked and cleared. In addition, the control provides

The save and load methods support persistence and reload. Kache was originally designed to store image caches and was later used

Because of the combination of expiration and archiving logic, most of the hit cache objects can be guaranteed.

All in the memory, thus obtaining high efficiency. You can get the Kache source code from Github for more information.

The preceding describes several data storage methods that are often used in iOS development.

The scenario is compared in a simple way. In fact, it is difficult for each application to use a single solution to complete the entire process.

The data storage task of the application needs to select the most appropriate solution based on different data types, so that the entire application can obtain

Good runtime performance.

SimpleCode example
Can I use databases for iOS development?

Yes, there is an API for operating sqlite in ios. That is to say, ios can operate the sqlite database.
In ios, in addition to using databases to solve relational data, we can also use core data.

Is the same database used for Android and ios software development?

Android and SQL use it as their default application database system.
The latest and mainstream versions of SQLite are 3.7, So we usually call it SQLite3.

Sqlite is a small relational database management system that complies with ACID application specifications. ACID is the first letter of an English word that is atomic, consistent, independent, and persistent, these four features are required by the database system for transaction processing.

The Android SDK has built-in SQLitem3 support.

There are many examples on the Internet for Baidu. We recommend that you learn the website from Android bus android.

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.