iOS - Persistence

data persistence

Persistent storage in iOS, that is, data will not be lost when the device is turned off and restarted, or the app is closed. In actual development, it is often necessary to hold stored data.

Advantages of data persistence:

  1. Quickly display and improve the experience
    The data that has already been loaded, when the user views it next time, does not need to be loaded from the network (disk) again, and is directly displayed to the user
  2. Save user traffic (save server resources)
    cache large resource data, no need to download and consume traffic for next display, reduce the number of server visits and save server resources
  3. Use offline.
  4. Record user actions

Data Persistence Solution in iOS

  • NSUserDefault simple data fast reading and writing
  • Property list file storage
  • Archiver
  • SQLite local database
  • CoreData

Classification of data holding methods

There are generally two types of data holding methods on the mobile terminal

memory cache

Definition: For data that is frequently used, after loading the data from the network or disk into the memory, it will not be destroyed immediately after use, and will be directly loaded from the memory next time.
The memory refers to the running space of the current program. The cache speed is fast and the capacity is small. It is used for temporary storage of files and can be directly read and written by the CPU. Open a program, it is stored in the memory, after closing the program, the memory will return to the original space.
the case

  • iOS system image loading - [UIImage imageNamed:@“imageName”]
  • Network image loading tripartite library SDWebImage

disk cache

Definition: Write the data loaded from the network and generated by user operations to the disk. When the user views and continues to operate next time, the disk is directly loaded from the disk. The disk is the
storage space of the program. The cache has large capacity, slow speed, and can be held. . Unlike memory, disks store things permanently.
the case

  • User input draft cache
  • Search history cache
  • Network image loading tripartite library SDWebImage

iOS sandbox mechanism

The sandbox mechanism in iOS is a security system. In order to ensure system security, each iOS application will create its own sandbox file (storage space) when it is installed. An application can only access its own sandbox files, and cannot access sandbox files of other applications. When an application needs to request or receive data from the outside, it must pass permission authentication, otherwise, the data cannot be obtained. All non-code files should be saved here, such as property files plist, text files, images, icons, media resources, etc. The principle is to direct the files generated and modified by the program to its own folder through redirection technology.

sandbox directory

Each APP sandbox has the following directory structure.
insert image description here

Application (application package):

Contains all resource files and executable files, which are digitally signed before release and cannot be modified after release.

Documents:

The document directory, to save the data generated by the program, will be automatically assigned to iCloud. Save the persistent data generated when the application is running, and this directory will be backed up when iTunes synchronizes the device. For example, a gaming app can save game saves to this directory. (Note: Do not save files downloaded from the Internet, otherwise they will not be available!)

Library:

1. User preference, use NSUserDefault to read and write directly!
2. If you want to write data to the disk in time, you need to call a synchronization method
3. Save temporary files, "need to use later", for example: cache pictures, offline data (the map data
system will not clean up the files in the cache directory, just When requesting program development, "a solution for cleaning the cache directory must be provided"
4.Caches: Store data that is large in size and does not need to be backed up
5.Preference: Save all preferences of the application, and iCloud will back up the setting information

Tmp:

Temporary files, the system will automatically clean up. A reboot will clean it up. Save the temporary data required by the application when it is running, and delete the corresponding files from this directory after use. The system may also clear the files in this directory when the application is not running. This directory is not backed up when iTunes syncs the device.

  1. Temporary files are stored and will not be backed up, and the data under this file may be cleared at any time
  2. Save temporary files, "do not need to use later"
  3. The files in the tmp directory will be automatically cleaned up by the system
  4. Restart the phone, the tmp directory will be cleared
  5. When the system disk space is insufficient, the system will also automatically clean up

Common ways to obtain the sandbox directory

  • Sandbox root directory:
 // 获取沙盒根目录路径
    NSString *path = NSHomeDirectory();
    NSLog(@"当前APP沙盒根目录路径为:%@", path);

Note: Each time the code is compiled, a new sandbox path will be generated. Note that the compilation is not started, so the simulation machine or the real machine runs, and the sandbox path obtained each time is different. The online version of the app is different from the real machine. A new sandbox path is generated.
insert image description here

insert image description here

Introduction to common C functions for accessing the sandbox directory

//文件路径搜索
FOUNDATION_EXPORT NSArray<NSString *> *NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory directory, NSSearchPathDomainMask domainMask, BOOL expandTilde);

The return value of this method is an array. Since there is only one unique path in the iPhone, you can directly take the first element of the array.

  • Parameter 1: Specify the directory name to search, for example, NSDocumentDirectory is used here to indicate that we want to search the Documents directory. If we replace it with NSCachesDirectory, it means that we are searching the Library/Caches directory.
typedef NS_ENUM(NSUInteger, NSSearchPathDirectory) {
    
    
    NSApplicationDirectory = 1,             // supported applications (Applications)
    NSDemoApplicationDirectory,             // unsupported applications, demonstration versions (Demos)
    NSDeveloperApplicationDirectory,        // developer applications (Developer/Applications). DEPRECATED - there is no one single Developer directory.
    NSAdminApplicationDirectory,            // system and network administration applications (Administration)
    NSLibraryDirectory,                     // various documentation, support, and configuration files, resources (Library)
    NSDeveloperDirectory,                   // developer resources (Developer) DEPRECATED - there is no one single Developer directory.
    NSUserDirectory,                        // user home directories (Users)
    NSDocumentationDirectory,               // documentation (Documentation)
    NSDocumentDirectory,                    // documents (Documents)
    NSCoreServiceDirectory,                 // location of CoreServices directory (System/Library/CoreServices)
    NSAutosavedInformationDirectory API_AVAILABLE(macos(10.6), ios(4.0), watchos(2.0), tvos(9.0)) = 11,   // location of autosaved documents (Documents/Autosaved)
    NSDesktopDirectory = 12,                // location of user's desktop
    NSCachesDirectory = 13,                 // location of discardable cache files (Library/Caches)
    NSApplicationSupportDirectory = 14,     // location of
  • Parameter 2 domainMask: NSSearchPathDomainMask type, the location of the search home directory, NSUserDomainMask indicates that the search scope is limited to the current application sandbox directory. NSLocalDomainMask (for /Library)
typedef NS_OPTIONS(NSUInteger, NSSearchPathDomainMask) {
    
    
    NSUserDomainMask = 1,       // user's home directory --- place to install user's personal items (~)// 
    NSLocalDomainMask = 2,      // local to the current machine --- place to install items available to everyone on this machine (/Library)
    NSNetworkDomainMask = 4,    // publically available location in the local area network --- place to install items available on the network (/Network)
    NSSystemDomainMask = 8,     // provided by Apple, unmodifiable (/System)
    NSAllDomainsMask = 0x0ffff  // all domains: all of the above and future items
};
  • Parameter 3 expandTilde: Whether to obtain the full path, the full-write form in iOS is /User/userName, the value is yes, which means the full-write form, if it is no, it is directly written as ~
    insert image description here
    insert image description here

Persistence solution implementation

Preferences preferences (UserDefaults)

Simple data is read and written quickly, and when the custom type
UserDefaults setting data cannot be stored, it is not written immediately, but the data in the cache is written to the local disk periodically according to the timestamp. So after calling the set method, the data may be terminated before being written to the disk. If the above problems occur, you can call the synchornize method [defaults synchornize]; to force writing.
Advantages of preference storage:
You don’t need to care about the file name, the system will automatically generate a file name for you
Quickly store key-value pairs
insert image description here

plist file

insert image description here
If the object is of type NSString, NSDictionary, NSArray, NSData, NSNumberetc., you can use
writeToFile:atomically:the method to directly write the object to the property list file
insert image description here

Archiver

Archiver is a way to persist data. The difference between it and Plist is that it can persist custom objects. But he is not as convenient as Plist.
The data that Archiver can persist by default includes NSNumber, NSArray, NSDictionary, NSString, and NSData, because these objects have already implemented the
protocol. Suppose we want to implement the Archiver persistence of an object, we must also implement the object. After iOS13, we must abide by the NSSecureCoding protocol. The NSSecureCoding protocol also follows the original NSCoding protocol, but we also need to follow its supportsSecureCoding method, so that we can archive successfully.

// 归档
-(void)testArchiver {
    
    
    NSArray* array = [NSArray arrayWithObjects:@"zhangsan",@"wangwu",@"list",nil];
       
        // NSHomeDirectory 获取根目录 stringByAppendingPathComponent 添加储存的文件名
        
         NSString* filePath = [NSHomeDirectory() stringByAppendingPathComponent:@"array.src"];
         BOOL success = [NSKeyedArchiver archiveRootObject:array toFile:filePath];
         if(success){
    
    
             NSLog(@"保存成功");
         }else {
    
    
             NSLog(@"未保存");
         }
}
// 解档
- (void)testReturn {
    
    
    NSString* filePath = [NSHomeDirectory() stringByAppendingPathComponent:@"array.src"];
    NSArray *array = [[NSArray alloc] init];
    array = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
    NSLog(@"%@",array);
}
+ (BOOL)supportsSecureCoding {
    
    
        return YES;
}

database storage

  • SQLite
    is currently the mainstream embedded relational database. Its main features are lightweight and cross-platform. Many embedded operating systems currently use it as the first choice for databases.
  • CoreData
    CoreData is a framework that appeared after iOS5. It is essentially SQLitean encapsulation of the right. It provides the function of object-relational mapping (ORM), that is, it can convert OC objects into data, save them in SQLitedatabase files, and save them. The data in the database is restored to OCobjects. In this process, there is no need to manually write any SQLstatements, CoreDatawhich encapsulates the operation process of the database and the conversion process of data in the database and OC objects. By CoreDatamanaging the data model of the application, the amount of code that needs to be written can be greatly reduced
  • FMDB
    is a third-party framework for processing data storage. The framework is an encapsulation of sqlite. The whole framework is very lightweight but flexible and more object-oriented.

What is serialization and deserialization and what are they used for?

  • Serialization: the process of converting an object into a sequence of bytes
  • Deserialization: restore a byte sequence into an object
  • Function: write the object to a file or database, and read it out

Guess you like

Origin blog.csdn.net/chabuduoxs/article/details/126196431