Data Persistence and compilation of static link libraries and App static links in the app development process

Source: Internet
Author: User

Data Persistence and compilation of static link libraries and App static links in the app development process

Record Data Persistence first.

Common Data Persistence solutions provided by iOS clients: NSUserDefaults stands for user settings, NSKeydArchiver stands for archiving, plist file storage, and SQLite databases (including the upper-layer Core Data and FMDB ).

Each solution has its own application scenario and scope, and cannot be generalized. However, we can extend the differences between data storage and complexity.

In addition to the above solution, record another solution: LevelDB represents the key-Value Pair database.

 

Common NSUserDefaults methods:

1. You can use the standard user settings [NSUserDefaults standardUserDefaults], or use the init method to initialize new user settings.

2. Obtain, set, and remove key-value pairs like using dictionaries

3. The synchronize method is not recommended.

 

Plist file storage:

1. The Code reads an existing plist file in the application and obtains a dictionary.

NSString * filePath = [[NSBundle mainBundle] pathForResource: @ "test" ofType: @ "plist"];

NSMutableDictionary * dic = [[NSMutableDictionary alloc] initWithContentsOfFile: filePath];

2. Save or create a plist file after modifying the data

[Dic writeToFile: filePath atomically: YES];

 

NSKeydArchiver and NSKeyedUnarchiver:

1. There is a class method for archiving: + (BOOL) archiveRootObject :( id) rootObject toFile :( NSString *) path;

The solution has a class method: + (nullable id) unarchiveObjectWithFile :( NSString *) path;

You can archive and archive an object directly.

2. If you need to operate on multiple key-value pairs, we recommend that you use the following method:

+ (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 *key in keyArray) {            NSObject *object = [dic objectForKey:key];            [archiver encodeObject:object forKey: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 *key in keyArray) {        NSObject *object = [unarchiver decodeObjectForKey:key];        [dic setObject:object forKey:key];    }        [unarchiver finishDecoding];    return dic;}

Archive initForWritingWithMutableData and finishEncoding. the unclassified initForReadingWithData and finishDecoding must be paired.

 

SQLite database:

If you have used relational databases such as SQL Server and MySQL, you can use them easily. However, the underlying SQL language is not user-friendly. Therefore, the upper-layer Core Data or FMDB class library is widely used.

 

File Operations:

First, focus on the method: FOUNDATION_EXPORT NSArray <NSString *> * resolve (NSSearchPathDirectory, NSSearchPathDomainMask domainMask, BOOL expandTilde); the first enumeration parameter represents the file directory, and the second represents the range domain, the third parameter indicates whether to add the complete relative path.

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

NSArray * paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES );

NSString * rootPath = paths [0];

2. supplement the sub-file path

NSString * fullPath = [rootPath stringByAppendingPathComponent: filename];

3. File Operations, mainly using the [NSFileManager defamanager manager] singleton object

+ (void)createArchivedRootFile{    NSString *rootPath = [self getAppArchivedFilesRootPath];        if (![[NSFileManager defaultManager] fileExistsAtPath:rootPath]) {        [[NSFileManager defaultManager] createDirectoryAtPath:rootPath withIntermediateDirectories:YES attributes:nil error:nil];    }}+ (void)clearArchivedFileWithName:(NSString *)filename{    NSString *rootPath = [self getAppArchivedFilesRootPath];    NSString *fullPath = [rootPath stringByAppendingPathComponent:filename];        if ([[NSFileManager defaultManager] fileExistsAtPath:fullPath]) {        [[NSFileManager defaultManager] removeItemAtPath:fullPath error:nil];    }}

 

In addition to the above record scheme, record the experience of using the key value to the database LevelDB.

Key-value pairs are preferred when the data volume is not large but database storage and operations are required. LevelDB originated from Google is one of the stars.

In the past, the client needs to store provincial and municipal address data and read the data when the user selects the address. If all the data in the province, city, and district is completely read every time, the memory usage is both large and unnecessary, because the user may only select a zone in the city to save.

If you split the Provincial and Municipal Data into several key-value pairs and establish a chain relationship, you can store the data in key-value pairs and quickly read the required data.

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

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

3. The number of key-value pairs at the third level is the city quantity, the key is the "province name. City name", and the value is the area name array.

4 ......

As shown above, all the data is stored in LevelDB as key-value pairs. As long as you know the key rules and names, you can get the corresponding data quickly, and excellent IO ensures performance.

This is a record of the previous article on LevelDB, You can first refer to: http://www.cnblogs.com/A-Long-Way-Chris/p/4864573.html

 

Compile static Link Library

Take LevelDB as an example. First go to download C ++ source code: https://github.com/google/leveldb

Use Xcode to create a static Link Library

1. Create a project and select a type.

 

2. Set the Project Build Phases, click the plus sign in the upper left corner of the Region, and select Add Headers Phase.

 

3. Click the plus sign to add the header file to be exposed, and drag it from the Project column to the Public column.

 

 

4. switch between the real machine and the simulator. After compilation is successful, right-click libleveldb. a In the Products directory and view it in the Finder.

 

5. Run cd in the terminal program to this directory and enter the following command to export a static link library that supports both real machines and simulators.

Lipo-create Debug-iphoneos/libleveldb. a Debug-iphonesimulator/libleveldb. a-output libleveldb.

 

Use the command line to compile the static Link Library of LevelDB through Makefile

1. decompress the downloaded package and use a text editor such as Visual Studio Code to open the Makefile in the directory.

2. Modify CXXFLAGS in Makefile, add the command-fembed-bitcode, and save

 

3. In the terminal, cd to the LevelDB directory and enter the command: CXXFLAGS =-miphoneos-version-min = 7.0 make PLATFORM = IOS

The static Link Library of iOS version is generated. The minimum version is 7.0 (this setting ensures normal operation on the simulator ).

If permission denied is prompted, add sudo to the preceding command and make sudo CXXFLAGS =-miphoneos-version-min = 7.0 make PLATFORM = IOS. then enter the password and press Enter.

 

4. Note that if you skip steps 1 and 2 and the generated LevelDB static Link Library does not support bitcode, you can see that the size difference is large, compile as needed

 

Add the header files in the. a file and the include directory to the project.

1. If a Header file cannot be found, check whether the Header Search Paths is missing in the project configuration.

2. If you use a version that does not support bitcode, you need to set enable bitcode to NO in build setting. This setting has the same requirements for other class libraries.

 

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

 

In the base project, I added the LevelDBHelper tool class to further encapsulate the calling code, making the operation simpler and safer.

 

Base project Updated: git@github.com: ALongWay/base. git

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.