【iOS】—— Persistence

The purpose of data persistence

  • Quick display, enhance experience
    • The data that has already been loaded does not need to be loaded from the network (disk) again when the user views it next time, and is directly displayed to the user
  • Save user traffic (save server resources)
    • Cache large resource data, no need to download and consume traffic for next display
    • At the same time, it reduces the number of visits to the server and saves server resources.
  • use offline
    • The data browsed by the user does not need to be connected to the Internet and can be viewed again.
    • Some functions are used to relieve the dependence on the network. (Baidu offline map, book reader)
    • When there is no network, the user is allowed to operate, and it will be synchronized to the server next time when the network is connected.
  • Record user actions
    • Draft: For operations that require a large cost for the user, each step of the user is cached. After the user interrupts the operation, the next user operation will directly continue the previous operation.
    • Read content tagging cache to help users identify what has been read.
    • Search history cache

Data persistence scheme in iOS

  • NSUserDefaultSimple data fast reading and writing
  • Property list(property list) file storage
  • Archiver(archive)
  • SQLitelocal database
  • CoreData

Classification of data persistence 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.

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 for direct reading and writing by the CPU. Open a program, it is stored in the memory, after closing the program, the memory will return to the original space.

  • 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, it will be directly loaded and used from the disk

The disk is the storage space of the program, the cache capacity is large, the speed is slow, and it can be held. Unlike memory, disks store things permanently.

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

Sandbox mechanism

Each iOS application has its own application sandbox. The application sandbox is the file system directory, which is isolated from the file system of other applications. The iOS system does not allow access to the application sandbox of other applications. Access has been opened in iOS8 (extension). Extension is an extension mechanism for several fixed system areas newly opened by iOS8, which can make up for the limitation of iOS's sandbox mechanism on communication between applications to a certain extent.

The application sandbox generally includes the following file directories: application package, Documents, Libaray (there are Caches and Preferences directories below), tmp.

  • 应用程序包: Contains all resource files and executable files.
  • Documents: Save the data that needs to be persisted generated when the application is running, and iTunesthis directory will be automatically backed up. Apple recommends saving the file data created in the program or browsed in the program in this directory, and iTunesthis directory will be included when backing up and restoring
  • tmp: Save the temporary data required for the application to run, and delete the corresponding files from this directory after use. When the application is not running, the system may also clear the files in this directory, and iTunesthe directory will not be synchronized. When the iPhone restarts, the files in this directory will be lost.
  • Library: Store the program's default settings and other status information, and iTunesthis directory will be automatically backed up.
    • Libaray/Caches: Store cache files, iTunesthis directory will not be backed up, and files in this directory will not be deleted when the application exits. Generally, the storage volume is relatively large and not particularly important resources.
    • Libaray/Preferences: Save all the preferences of the application, the iOS Settings(Settings) application will search for the application's setting information in this directory, and iTuneswill automatically back up this directory.

Get the sandbox path of the application

// 获取沙盒根目录路径
NSString *path = NSHomeDirectory();

Notice:Every 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, and the online version of the app will not be generated on the real machine. The new sandbox path.

The above code gets the path of the current application directory, which is the sandbox of the application, and there are 4 folders in this directory: , , , , and the current application can only Documentsaccess Librarythe SystemDatafiles tmpin this directory.

How to get the sandbox directory

//获取沙盒根路径
NSString *path = NSHomeDirectory();
NSLog(@"沙盒根路径:%@", path);
//Document路径
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSLog(@"Document目录路径:%@", docDir);
// 获取Library的目录路径
NSString *libDir = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) lastObject];
NSLog(@"Libarary目录路径:%@", libDir);
// 获取Caches目录路径
NSString *cachesDir = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
NSLog(@"Cacheas目录路径:%@", cachesDir);
// library Preference
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSLog(@"偏好设置目录路径:%@", defaults);
// 获取tmp目录路径
NSString *tmpDir =  NSTemporaryDirectory();
NSLog(@"tmp目录路径:%@", tmpDir);

Output result:
insert image description here

Persistent data storage method

XML attribute list

A property list is a file in XML format with the extension plist.

If the object is of type NSString, , NSDictionary, NSArray, NSDataetc. NSNumber, you can use
writeToFile:atomically:the method to directly write the object to the property list file, for example:

    // 获取 Document 文件目录
    NSString *docPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    // 在 Document 目录下新建一个 test.plist 文件
    NSString * filePath = [docPath stringByAppendingPathComponent:@"test.plist"];

    // 存字典,将字典数据存到刚才的 test.plist 文件
    NSDictionary* dict = @{
    
     @"name" :@"zxb10", @"age" : @"20" };
    [dict writeToFile:filePath atomically:YES];

    // 取字典,从刚才的 test.plist 文件中取出字典数据
    NSDictionary* dictA = [NSDictionary dictionaryWithContentsOfFile:filePath];
    NSLog(@"%@", dictA);

    // 存数组
    NSArray* array = @[@"zxb10", @"20"];
    [array writeToFile:filePath atomically:YES];

    // 取数组
    NSArray* arrayA = [NSArray arrayWithContentsOfFile:filePath];
    NSLog(@"%@", arrayA);

Output result:
insert image description here
We can find this file in the document directory:
insert image description here
because we finally stored the NSArray data type, so it is the NSArray type data here.

Preferences preferences (UserDefaults)

Many iOS applications support preference settings, providing a set of standard solutions to add preference settings functions to the application, such as saving user name, font size, password, whether to automatically log in, etc.

Each application has an NSUserDefaultsinstance through which preferences can be accessed, no path required. The creation of itself is similar to the singleton mode. We apply for creation again later with different attribute names, which will overwrite the previous data.

NSUserDefaults: Simple data can be read and written quickly, and cannot store custom types.
UserDefaultsWhen setting data, instead of writing it immediately, the data in the cache is written to the local disk periodically according to the timestamp. So after the method is called set, the data may not be written to the disk and the application terminates. If the above problems occur, you can force writing by calling synchornizethe method [defaults synchornize];.

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.

Let's UserDefaultstry to register an account password:

    // 获取偏好设置对象
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

    //存储数据
    [defaults setObject:@"zxb10" forKey:@"name"];
    [defaults setObject:@"zxbnb666" forKey:@"password"];

    // 同步调用,立刻写到文件中,不写这个方法会异步,有延迟
    [defaults synchronize];

    // 需要验证账号密码的地方,获取偏好设置对象
    NSUserDefaults *defaultsA = [NSUserDefaults standardUserDefaults];
    NSString *name = [defaultsA objectForKey:@"name"];
    NSString *password = [defaultsA objectForKey:@"password"];
    NSLog(@"name:%@ password:%@", name, password);

insert image description here

database storage

  • SQLite:
    It is currently the mainstream embedded relational database. Its main feature is lightweight and cross-platform. Many embedded operating systems currently use it as the first choice for databases.
  • CoreData:
    CoreData is a framework that only appeared after iOS5.Essentially an encapsulation of SQLite, 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 can also restore the data stored in the database into OC objects. In this process, no Manually write any SQL statement, CoreData encapsulates the operation process of the database, as well as the conversion process of data and OC objects in the database. By managing the data model of the application through CoreData, the amount of code that needs to be written can be greatly reduced.
  • FMDB:
    It 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.

SQLiteand CoreDatathe difference between:

  • CoreDataWhen an object is updated, its associated objects will also be updated, which means that when you update a table, other associated tables will also be updated.
  • CoreDataFor a simpler performance management mechanism, you can limit the total number of query records, this class will automatically update its cache.
  • In terms of multi-table query, CoreDatait is not as intuitive as SQL, and there are no operations such as outer join and left join.

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

Write and read plist files

// 其中,Show为我们plist文件的名称,后面的plist是Show的扩展名
// 写入plist
- (void)setDataFromPlist {
    
    
    NSString *plist = [[NSBundle mainBundle] pathForResource:@"Show" ofType:@"plist"];
    NSMutableDictionary *temp = [[NSMutableDictionary alloc] init];
    [temp setValue:@20 forKey:@"age"];
    [temp setValue:@"男" forKey:@"sex"];
    [temp writeToFile:plist atomically:YES];
}

// 读取plist
- (void)getDataFromPlist {
    
    
    NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"Show" ofType:@"plist"];
    NSMutableDictionary *dataDic = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
    NSLog(@"%@", dataDic);//直接打印数据
}

Guess you like

Origin blog.csdn.net/m0_62386635/article/details/131811289