Data persistence and compilation of the app development process static link library

Source: Internet
Author: User
Tags sqlite database

Record data persistence first.

Common data persistence scenarios provided by iOS clients: Nsuserdefaults represents the user settings, Nskeydarchiver represents the archive, plist file storage, SQLite database (including core Data,fmdb used on top).

Each scenario has its own application scenario and scope and cannot be generalize. However, it can be roughly differentiated by the amount of data stored and the complexity.

In addition to the above mentioned scenarios, a scheme is recorded: Leveldb represents a key-value pair of databases.

Nsuserdefaults Common methods:

1. You can use standard user settings [nsuserdefaults standarduserdefaults], or initialize new user settings with Init-related methods

2. Get, set, remove key-value pairs as you would with a dictionary

3.TheSynchronize method has not been recommended for use

plist file Storage:

1. The code reads the plist file that already exists in the application and gets a dictionary

NSString *filepath = [[nsbundle mainbundle] pathforresource:@ "Test" OfType :@ "plist"];

nsmutabledictionary *dic = [[nsmutabledictionary alloc] initwithcontentsoffile : FilePath];

2. After modifying the data, save or create the plist file

[DiC writetofile: FilePath atomically:YES];

Nskeydarchiver and Nskeyedunarchiver:

1. An archive has a class method: + (BOOL) Archiverootobject: (ID) rootobject tofile: (nsstring *) path;

The solution has a class method:+ (nullable ID) unarchiveobjectwithfile: (nsstring *) path;

An object can be archived and reconciled directly.

2. However, if you need to operate on multiple key-value pairs, it is recommended that you use the following methods:

+ (void) Archivedatawithdictionary: (nsdictionary *) dic filename: (nsstring*) filename Archivesuccessblock: (archivesuccessblock) archivesuccessblock{nsstring*fullpath =[self getapparchivedfilefullpathwithname:filename]; Dispatch_async (Dispatch_get_global_queue (Dispatch_queue_priority_default,0), ^{nsmutabledata*data =[Nsmutabledata data]; Nskeyedarchiver*archiver =[[Nskeyedarchiver alloc] initforwritingwithmutabledata:data]; Nsarray*keyarray =[Nsarray arraywitharray:[dic AllKeys];                [Archiver Encodeobject:keyarray Forkey:filename];  for(NSString *keyinchKeyarray) {NSObject*Object=[dic Objectforkey:key]; [Archiver encodeobject:ObjectForkey:key];        } [Archiver finishencoding];                [Data Writetofile:fullpath Atomically:yes]; if(Archivesuccessblock) {archivesuccessblock (); }    });}+ (Nsdictionary *) Unarchivedatawithfilename: (NSString *) filename{nsmutabledictionary*dic =[Nsmutabledictionary dictionary]; NSData*data =[[NSData alloc] initwithcontentsoffile:[self Getapparchivedfilefullpathwithname:filename]]; Nskeyedunarchiver*unarchiver =[[Nskeyedunarchiver alloc] initforreadingwithdata:data]; Nsarray*keyarray =[Nsarray arraywitharray:[unarchiver decodeobjectforkey:filename];  for(NSString *keyinchKeyarray) {NSObject*Object=[Unarchiver Decodeobjectforkey:key]; [DiC setobject:ObjectForkey:key];    } [Unarchiver finishdecoding]; returnDiC;}

Archived initforwritingwithmutabledata and finishencoding, initforreadingwithdata of the files and Finishdecoding need to appear in pairs.

SQLite database:

As long as the use of a relational database such as SQL Server and MySQL can be easily used, but the underlying SQL language is not very human, so the general use of the upper core data or Fmdb class library.

File operation:

First approach:foundation_export nsarray<nsstring *> *nssearchpathfordirectoriesindomains ( nssearchpathdirectory directory, nssearchpathdomainmask domainmask, BOOL Expandtilde) The first enumeration parameter represents the file directory, the second represents the Range field, and the third parameter indicates whether to complement the complete relative path

1. Get the current user's doc file root directory:

Nsarray *paths = nssearchpathfordirectoriesindomains(nsdocumentdirectory, Nsuserdomainmask, YES);

nsstring *rootpath = paths[0];

2. Supplemental sub-file path

nsstring *fullpath = [RootPath stringbyappendingpathcomponent: filename];

3. File operation, mainly used [nsfilemanager defaultmanager] Singleton object

+ (void) createarchivedrootfile{NSString*rootpath =[self getapparchivedfilesrootpath]; if(![[Nsfilemanager Defaultmanager] Fileexistsatpath:rootpath]) {[[Nsfilemanager Defaultmanager] Createdirectoryatpath:rootpath withintermediatedirectories:yes attributes:nil err    Or:nil]; }}+ (void) Cleararchivedfilewithname: (NSString *) filename{NSString*rootpath =[self getapparchivedfilesrootpath]; NSString*fullpath =[RootPath Stringbyappendingpathcomponent:filename]; if([[[Nsfilemanager Defaultmanager] Fileexistsatpath:fullpath]) {[[Nsfilemanager Defaultmanager] RemoveItemAtPat    H:fullpath Error:nil]; }}

In addition to the above recording scheme, record the use of key values on the database LEVELDB experience.

When the amount of data is not very large, but also requires database storage and operation, the key value for the database is preferred. Leveldb from Google is one of the stars.

Previously encountered the client storage of provincial and municipal address data requirements, and when the user selects the address to read the relevant data. If you read the provincial and municipal data completely each time, it is not necessary to take up the memory, because the user is likely to select only one area of the saved city.

If the data of the province is divided into several key-value pairs, and a chain relationship is established, the data can be stored in a key-value pair somewhere, and the data needs to be read quickly.

1. The first level has only one key-value pair, the key is a fixed value, the value is the name array of all provinces

2. The second-level key-value pairs are in the province quantity, the key is the province name, the value is the city name array

3. The number of key-value pairs in the third tier is the number of cities, and key is the province name. City name, value is an array of zone names

4 ...

As above, the data are all stored in LEVELDB with key-value pairs, as long as you know the key rules and names, you can quickly fetch the corresponding data, and excellent IO to ensure performance.

This is a previously recorded article about Leveldb, you can refer to the first: http://www.cnblogs.com/A-Long-Way-Chris/p/4864573.html

Compiling a static link library

Just take leveldb as a case. Previous download C + + source code: HTTPS://GITHUB.COM/GOOGLE/LEVELDB

Create a static-link library with Xcode

1. Create a new project, select a type

2. Set the project build phases, click the plus sign in the upper left corner of the area, select Add Headers Phase

3. Click the plus sign to add a header file that needs to be exposed, then drag from the project bar to the public bar

4. Switch between the real machine and the simulator, respectively, after the successful compilation, right-click the LIBLEVELDB.A in the Products directory, view in finder

5. In the Terminal program CD to the directory, enter the following instructions, you can export both the real machine and emulator run static link library

Lipo-create DEBUG-IPHONEOS/LIBLEVELDB.A debug-iphonesimulator/libleveldb.a-output LIBLEVELDB.A

Using the command line, compile the Leveldb static link library via makefile

1. After unpacking the download package, open the directory using a text editor such as visual Studio code makefile

2. Modify the Cxxflags in makefile, add instruction-fembed-bitcode, save

3. In the terminal, CD to LEVELDB directory, input directive:cxxflags=-miphoneos-version-min=7.0 make Platform=ios

Represents a static-link library that builds an iOS version with a minimum version of 7.0 (which is guaranteed to work correctly on the emulator).

If prompted permission denied, precede the above instruction with sudo and, ultimately: sudo cxxflags=-miphoneos-version-min=7.0 make Platform=ios, then enter the password to return.

4. Note that if you skip steps 1 and 2, the last generated leveldb static link library does not support Bitcode, you can see the volume difference or relatively large, on-demand compilation

Add the. A file and the header file in the Include directory to the project for normal use.

1. If you are prompted that a header file could not be found, check the project configuration, header Search paths if there is a missing configuration

2. If you are using a version that does not support Bitcode, you will need to set the Enable Bitcode to No in build setting. This setting is the same for other class library requirements

In order to facilitate the use of OC programming, but also introduced another class library, the LevelDB code is OC encapsulated, address: Https://github.com/matehat/Objective-LevelDB

In the base project, I added the Leveldbhelper tool class, which further encapsulates the calling code and makes the operation simpler and more secure.

The base project has been updated: [Email protected]:alongway/base.git

Data persistence and compilation of the app development process static link library

Related Article

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.