IOS data persistence

Time:2021-12-1
IOS data persistence

image.png

Content of this article:
Several types of IOS local data persistence
Several types of application scenarios and usage of IOS local data persistence

1、 Types of IOS local data persistence:

-NSUserDefaults

-plist

-Keychain

-Filing

-Sandbox write

Database

2、 Application scenario

1,NSUserDefaults

It is used to store user preferences and user information, such as user name, automatic login, font size, etc
The data is automatically saved in the library / preferences directory of the sandbox
Nsuserdefaults stores the input data in a file in. Plist format. This storage method determines that its security is almost 0. Therefore, it is not recommended to store some sensitive information, such as user password, token, encrypted private key, etc!
The data types it can store are: nsnumber (nsinteger, float, double), nsstring, nsdate, nsarray, nsdictionary, bool
Storage of custom objects is not supported

NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    [userDefault setInteger:1 forKey:@"integer"];
    [userDefault setBool:YES forKey:@"BOOl"];
    [userDefault setFloat:6.5 forKey:@"float"];
    [userDefault setObject:@"123" forKey:@"numberString"];
    NSString *numberString = [userDefault objectForKey:@"numberString"];
    BOOL myBool = [userDefault boolForKey:@"BOOl"];
    [userDefault removeObjectForKey:@"float"];
    [userDefault synchronize];

Problems needing attention:
The data stored in nsuserdefaults is immutable. If you want to store variable data, you need to turn it into immutable before you can store it
Nsuserdefaults writes the data in the cache to the disk regularly rather than immediately. To prevent data loss caused by program exit after writing nsuserdefaults, you can use synchronize to force the data to be written to the disk immediately after writing the data

2,plist

That is, the property list file. Its full name is property list. The extension of this file is. Plist. Therefore, it is usually called plist file. It is a file used to store serialized objects. It is used to store data that is often used in programs and has a small amount of data that is not often changed.
Types that can be stored: nsnumber, nsstring, nsdate, nsdata, nsarray, nsdictionary, bool
Storage of custom objects is not supported

Plist can be created in two ways: Command + n creation and pure code creation. Different creation methods and use methods are naturally different

Command + n create:
Creation: (creation method: Baidu)
Read:

NSString *plistPath = [[NSBundle mainBundle]pathForResource:@"myTest" ofType:@"plist"];
    NSMutableDictionary *dataDic = [NSMutableDictionary dictionaryWithContentsOfFile:plistPath];
    /**If it is an array*/
//    NSMutableArray *dataArray = [NSMutableArray arrayWithContentsOfFile:plistPath];
    NSLog(@"%@",dataDic);

modify

[datadic setobject: @ "male" forkey: @ "sex"];
[dataDic setObject:@15 forKey:@"age"];
[dataDic writeToFile:plistPath atomically:YES];
NSLog(@"----%@",dataDic);

Pure code creation:
establish:

NSArray *sandBoxPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [sandBoxPath objectAtIndex:0];
NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"myTestPlist.plist"];
    NSLog(@"%@",plistPath);

write in

NSMutableDictionary *dic = [NSMutableDictionary dictionary];
[dic setObject:@"18" forKey:@"age"];
[DIC setobject: @ "Populus euphratica" forkey: @ "name"];
[dic writeToFile:plistPath atomically:YES];

Read:

NSArray *sandBoxPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsPath = [sandBoxPath objectAtIndex:0];
    NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"myTestPlist.plist"];
    NSLog(@"%@",plistPath);
    NSMutableDictionary *dataDic = [NSMutableDictionary dictionaryWithContentsOfFile:plistPath];
    NSLog(@"-----%@",dataDic);

Modification:
The method is the same as command + n

Problems needing attention:
If you need to store custom type data, you need to serialize it first!

3,Keychain

It is used to store important local data. It is safer to store the data locally after encryption, such as password, secret key, serial number, etc. when you delete the app, the data stored in Keychain will not be deleted, so the data in Keychain can still be used after reinstalling the app. Since IOS 3.0, it has become feasible to share Keychain across programs, and the data stored in nsuserdefaults will be deleted with the app
When using keychain, Apple has officially encapsulated the file keychainitemwrapper for us, which can be used after introduction. Of course, other excellent third-party packages, such as sskeychain, can also be used as follows:
usage method

4. Archive (nskeyedarchiver)

Archiving is a common technique for data storage in IOS development. Archiving can directly store objects as files and read files as objects.
Compared with plist or userdefault, archiving can store more data types and access custom objects. The file archived by the object is confidential. The contents of the file cannot be viewed on the disk, which is more secure.
Comply with the nscoding protocol and implement the two methods in the protocol. If it is inheritance, the subclass must override the two methods. When a subclass accesses, it will look for the called method in the subclass. If it fails to find it, it will look for it in the parent class. Therefore, the newly added properties will be ignored when saving and reading. You need to call the method of the parent class first, initialize the method of the parent class first, and then initialize the method of the child class.
The suffix name of the file where the data is saved can be named at will.
demo

5. Sandbox writing

It is persistent in the document directory and generally stores non confidential data. When the app involves e-book reading, listening to music, watching videos, brushing picture lists, etc., it is recommended to use sandbox storage. Because this can greatly save user traffic and enhance the experience effect of the app

Application: store the program source file. It is digitally signed before it is put on the shelf and cannot be modified after it is put on the shelf.
Documents: save the data that should be generated at runtime and need to be persisted. ITunes will back up the directory when it synchronizes the device. For example, the game application can save the game archive in this directory.
TMP: save the temporary data required for operation, and then delete the corresponding files from the directory after the completion of. When the application is not running, the system may also clear the files in this directory. This directory is not backed up when iTunes syncs the device.
Library / caches: save the data that needs to be persisted when the application runs. ITunes will not back up the directory when synchronizing the device. Generally, non important data with large storage volume and no need to be backed up, such as network data cache, are stored in caches
Library / preference: save all preference settings of the application, such as settings of IOS. You should find the setting information in this directory. This directory is backed up when iTunes syncs the device.

//Get the home directory of the program       
NSString  *path = NSHomeDirectory();     
//Get document directory       
NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;  
//Get cache directory       
NSString *path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject;   
//Get Library Directory       
NSString *path = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES).firstObject;
//Get TMP directory       
NSString *path = NSTemporaryDirectory();

write in

NSString *path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject;
NSString *filePath = [path stringByAppendingPathComponent:@"test.txt"];
NSLog(@"%@",filePath);
NSArray *array = @[@"1",@"2",@"3"];
    BOOL isSuccess = [array writeToFile:filePath atomically:YES];
    if (isSuccess) {
        Nslog (@ "success");
    } else {
        Nslog (@ "failed");
    }

Read:

NSString *path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject;
    NSString *filePath = [path stringByAppendingPathComponent:@"test.txt"];
    NSLog(@"%@",filePath);
NSArray *tmpArray = [NSArray arrayWithContentsOfFile:filePath];
    NSLog(@"%@",tmpArray);

6. Database

It is suitable for storing large amount of data, which is generally realized by fmdb and coredata

FMDB:
Fmdb is the SQLite database framework of IOS platform. Fmdb encapsulates SQLite’s C language API in the form of OC, which is more object-oriented and saves a lot of trouble and redundant C language code. Compared with Apple’s own core data framework, fmdb is more lightweight and flexible, provides a multi-line safe database operation method, and effectively prevents data confusion.

CoreData:
Core data is a framework that emerged after ios5. It provides the function of object relational mapping (ORM), that is, it can convert OC objects into data and save them in SQLite database files, and restore the data saved in the database into OC objects. During this data operation, we do not need to write any SQL statements. However, it is not so easy to directly operate coredata, so I will use magicrecord most of the time. Magicrecord is the secondary encapsulation of coredata, which is simple to use and easy to operate

Original text:https://blog.csdn.net/u010389309/article/details/88369088