iOS data storage

Source: Internet
Author: User

"Reference" Http://www.infoq.com/cn/articles/data-storage-in-ios

When it comes to data storage, it is first clear to distinguish between two concepts, data structures and storage methods. The so-called data structure is the existence of the form. In addition to the basic nsdictionary, Nsarray, and Nsset objects, there are more complex structures such as relational models, object graphs, and attribute lists. The storage method is simply divided into two types: memory and Flash. Memory storage is temporary, run-time efficient, but efficient, while Flash is a persistent storage, but produces I/O consumption, the efficiency is relatively low. Moving memory data into the flash to persist operations is called archiving.

The combination of the two is the complete data storage scheme, the most talk about of those: SQLite, CoreData, nsuserdefaults, etc. are data storage solutions. Of course, in addition to the solutions provided by these frameworks, we can tailor our own solutions to individual needs. These storage schemes focus on different forms and modes of support, and each has its merits and demerits in different usage scenarios. But original aim, no matter what program can be used to explain.

Figure 1, storage scenarios

The following four storage methods are described in detail:

    • Nsuserdefaults, for storing configuration information
    • SQLite for storing data with more demanding queries
    • CoreData, for planning objects in your app
    • Customized caching schemes using basic object types

Storing configuration information with Nsuserdefaults

Nsuserdefaults is designed to store configuration information for devices and applications, and it returns the default, and most commonly used, instance objects through a factory method. This object stores the configuration information of the user in the system, which can be modified by the instance object, or the new configuration items can be created according to their own requirements.

Figure 2, the author [nsuserdefaults Standarduserdefaults] content in the phone

NSUSERDEFAULTS organizes configuration information into dictionaries, including strings or arrays, and supports basic formats such as numbers. A nutshell is: A dictionary of basic types of small data. The method of operation is almost identical to that of the nsdictionary, and the return value of the specified type can be obtained by specifying a method of the return type.

Figure 3,nsuserdefaults provides a list of methods for the specified return type

All the data in the Nsuserdefaults is in memory, so the operation is fast and provides an archive method: + (void) synchronize. Developer-defined configuration items (the last item in 2 KEY:ALKDJFKLADSJFMM) are archived in plist format for/library/preferences/[app_bundle_identifier] in the appropriate application directory. plist file. Once the instance object has been initialized again, the framework merges the user-defined configuration and system configuration to get the complete data.

Query for more demanding data with SQLite storage

In the iOS SDK, the SQLite library is provisioned, and developers can build their own SQLite database. Each time SQLite writes data, it generates IO consumption and archives the data to the appropriate file.

SQLite is good at dealing with data types that are similar to nsuserdefaults and are basic types of small data, just different from the organization. Developers can organize data in a relational database, using SQL DML to manage the data. Generally speaking, the formatted text class data in the application can be stored in the database, especially the data such as chat record, timeline and so on which have conditional query and sorting requirements.

Each database handle will be allocated a cache in memory to improve query efficiency. Another aspect, because the query cache, when generating a large number of handles or large amounts of data, the cache is too large, resulting in memory waste.

SQLite is more complex to use than nsuserdefaults, so it is recommended that developers use SQLite with an action control to simplify the operation. The sqlight developed by the author is a package for sqlite operation, which encapsulates the relatively complex SQLite commands into objects and methods, which can be referenced by everyone. You can get a closer look at the code for this project on GitHub.

Use CoreData to plan objects in your app

The official definition is an automated management scheme that supports persistence, object graphs, and lifecycles. Strictly speaking, CoreData is a management solution, and his persistence can be stored through SQLite, XML, or binary files. As the official definition says, the role of CoreData is far more than storing data so simple that it can model and automate the management of objects throughout the application.

Figure 4, an example of an object diagram given in an official document explaining CoreData

As shown, mydocument is an object instance with two Collection:employee and department that hold the respective list of objects. The MyDocument, employee, and department three objects and their relationships are modeled by CoreData and can be persisted through the Save method.

When you restore a model from an archive file, CoreData does not load all the data in the entire model into memory at once, but instead loads the object instances that were invoked into memory based on the runtime state. The framework automatically controls this process to control memory consumption and avoid waste.

CoreData are more complex, both in terms of design principles and methods of use. Therefore, CoreData is definitely not a preferred option if you are only considering the need for caching data. The CoreData scenario is that the entire application uses CoreData planning to model the data in-app through CoreData, based entirely on the CoreData architecture application.

Apple's official example code, the structure is relatively simple, can help you get started coredata.

Customized caching schemes using basic object types

The previously mentioned nsuserdefaults and SQLite are suitable for storing small data of the underlying type, while CoreData is not suitable for storing a single piece of data, so what is the way to store larger data like images? My advice is to implement a set of storage solutions. When it comes to custom storage solutions, it's very easy to question whether it's reinventing the wheel. I can tell you very clearly that this is by no means reinventing the wheel. First of all, it is clear that this so-called custom program for the Internet application of remote data caching, a few constraints are indispensable.

Analyze the requirements of cache data from demand: Search by key, fast read, write does not affect normal operation, do not waste memory, support archiving. These are the basic requirements, then you may need to fix the number of cache entries, support queue cache, cache expiration, and so on. From these requirements to design a caching scheme is not very complex, Kache is the author according to the needs of development and application of a set of cache components, through the analysis of Kache hope can give you a thought.

Figure 5,kache Frame composition

As shown, Kache plays a typical cache role. While the application loads the remote data to generate the application data object, it caches the data through Kache and requests the data directly through Kache.

Cached objects can be nsdictionary, Nsarray, Nsset, or NSData, which can be directly archived, each of which corresponds to a key. Cached objects include data and expiration times, in memory in a single dictionary, and each object in the flash is stored as a file. The key space holds the key collection of the cached object in various order, the pool is a fixed-size array, when the number reaches the upper limit, a key with the earliest expiration is deleted, and the corresponding cache object is cleared. The queue is also a fixed-size array that manages key additions and deletions with FIFO rules. Each time a new cache object is saved, the expired collection in the key space is automatically detected and cleared.

Additionally, the control provides the save and load methods to support persistence and re-loading.

Kache was originally designed to store image caches, which were then used to cache text data, and because of the combination of outdated and archived logic, it was possible to ensure that most of the hit cache objects were in memory, resulting in high efficiency. Readers can get Kache source code from GitHub to learn more.

This paper introduces several methods of storage data which are often encountered in iOS development, and makes a simple comparison from its storage principle, usage mode and applicable scene. In fact, each application is difficult to use a single solution for the entire application of data storage tasks, depending on the data type, choose the most appropriate solution for the entire application to achieve good runtime performance.

iOS data storage

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.