iOS Rampage---How data is stored in iOS app analytics

Source: Internet
Author: User
Tags object serialization

First, preface

The view controller knowledge points in iOS apps have been described in the previous article, and this article does not introduce the knowledge points of the view in common sense, but rather introduces the data storage knowledge points in iOS because there are too many knowledge points about view, followed by a series of detailed descriptions. This article first looks at the data storage feature analysis in iOS. Every iOS app, like Android apps, has its own sandbox for storing its own data, but the difference between iOS and Android is that there is no concept of an SD card, and that data that is applied to iOS can only be saved in its own sandbox. This can also be seen in iOS for security reasons of application.

When developing Android, we know the main storage methods are: Database, SD card, Sharedpreferences.xml, other directory of application sandbox, data serialization to local file, network, etc. In fact, in addition to the SD card in iOS, the other is similar to the other, so this article will introduce four ways to store: database, preferences, archive files, plist file. The follow-up to the network is described in detail separately. This is not the introduction. Let's start by introducing these four storage methods.


two, sandbox mechanism and sandbox directory structure

Before explaining these four ways, we have to do one thing first, is to understand the iOS application sandbox directory structure, Android is actually similar, the sandbox data are placed under the/data/data/xxxx/, the database is in the databases directory, Sharedpreferences.xml is stored in the Shared_prefs directory, as well as the files directory, the cache directory, and so on. The structure is very similar in iOS:

iOS apps are limited to "sandbox" and "sandbox" is the equivalent of a folder with owner-only visible permissions, and Apple has several restrictions on the sandbox.
The 1> application can operate in its own sandbox, but it cannot access the sandbox of any other application.
Data cannot be shared between 2> applications, files in the sandbox cannot be copied to other application folders, and files in other application folders cannot be copied into the sandbox.
3> Apple prohibits any reading or writing of files outside the sandbox, and prevents the application from writing content to a folder other than the sandbox.
4> There are three folders in the root directory: documents, you should generally store the application data files in this folder for storage functions.
A sandbox mechanism is a security system that specifies that an application can only read files in the application sandbox and cannot access content elsewhere. All non-code files are saved in this place, such as slices, audio, video, attribute lists (preferences) and text files.

Pros: It is safe for each application to be free to access the contents of another application sandbox within its own sandbox, and the application requests or accepts data out of the box that requires permission authentication
Cons: File access restricted access files are not flexible

Get sandbox path in iOS using the nshomedirectory () method, we can print a look at the effect, generally use the simulator when the directory is very long, we can use the finder command+shift+g go to the folder to export the sandbox path it prints:


We can copy this path to see this directory:


As we can see the nshomedirectory () gets the program's home directory, there are three subdirectories:Documents, Library, TMP

1, the library has caches and preferences directory

1 Caches: Saves data that needs to be persisted when the app runs, and itunes syncs the device without backing up the directory. Non-critical data that is typically stored in large volumes and does not require backup.
2 Preferences: Save all your app's preferences, and the iOS settings (settings) app will find the app's settings in that directory. The directory is backed up when itunes synchronizes the device.

2. Documents: Saves data that needs to be persisted when the app runs, and it backs up the directory when itunes synchronizes the device. For example, a game app can save a game archive in that directory.
3. tmp: Save the temporary data required for the application to run, and then delete the corresponding files from the directory when you have finished using them. When the app is not running, the system may also purge files in that directory. itunes does not back up the directory when syncing the device.

Then we generally get these directories in a number of ways:

The first approach is constructed directly from the directory name: For example, the documents directory:
[Nshomedirectory () stringbyappendingpathcomponent:@ "Documents"];

The others are similar. In this way there is a bad thing is that the file directory is manually written to die, which day if Apple said not to call this file directory name, then there is a big problem.
The second approach is obtained entirely using a system-provided approach: For example, the documents directory:
[Nssearchpathfordirectoriesindomains (Nsapplicationdirectory, Nsuserdomainmask, YES) [0];

If you want to create a new file in this directory, you can use NSString's stringbyappendingpathcomponent: method to get the file path name.


In fact, this is a simple introduction to the iOS program sandbox data directory structure, the following will begin to introduce the four kinds of storage, but before the introduction for the convenience of the next work, here we give the NSString class to define a classification , Add one to get the file name path method under the Documents directory , so that we can just import this classification, and then use the NSString method directly to obtain the file name under the documents directory, Otherwise every time to construct a documents path a little laborious, but also here can see the role of classification, classification definition is very simple, such as here is to add a classification for nsstring, then the classification name is nsstring+xxx.h can. where xxx is a name that can be casually started.


Later, if we want to create a new Demo.data file in the documents directory, we can do this directly: [@ "Demo.data" Documentappend] method call. You can see the specific usage later.


Three, storage mode analysisThe first type: Archive solution

This is actually very simple, is the concept of serialization in Java, you can turn an object into a byte stream data, in Java can be operated through the ObjectInputStream and ObjectOutputStream streams, However, there is a requirement that the manipulated object must implement the serialized interface: Serializable. Here the archive and the principle of operation similar, if you want to turn an object into a NSData object (NSData object is very common in iOS, a bit like the Bytebuffer class in Android, is the binary data stream, the operation is very convenient, such as read and write files, Network data to use it), and then write to the file. Of course, in this case, like Java, the operating class must implement a protocol: Nscoding, it is only the object that implements this protocol can be archived and file. The following is not much to say directly to see the code:

Here for the convenience of demonstration, create a new student class, implement the Nscoding protocol, and then file the operation, in the operation of the solution:


For convenience, a property is defined here. Then after defining this object, you need to implement the method in the protocol:


Here need to implement two methods, one is the object encoding method, one is the object decoding method, from here can see this more like Android parcel class, in fact, in Android we generally use the most is the parcel class, Mainly used for interprocess communication data transmission process , but generally do not write this class to the file, but also can be implemented, you can read and write to the file through the Marshall and Unmarshall two methods . But it doesn't seem like the door is dry. Serializable is generally used for serialization, so I did not mention the parcel class at the beginning. In fact, this nscoding protocol is more similar to the Parcelable interface. It's not hard to write about the parcel class in Android. Once you've defined this class, we can start archiving and reconciling files:


See the code here is very simple, at the same time using the above classification function, here you can see the code is much reduced. Archive using Nskeyedarchiver:tofile: method. The solution uses the Nskeyedunarchiver: method. We can check out this file information:


It's just a binary data file.


the second type: app Preferences

This is very similar to Sharedpreferences.xml in Android, but in iOS you will find that this is much easier to store than Android. When you remember to manipulate sp.xml in Android, there are several lines of code for read and write operations. There is also the difference between apply and commit. Also consider performance issues. Saving a value in iOS is a line of code that reads a value and is a single line of code. Here's a quick look at the code case:


The main use of the Nsuserdefaults class to operate, you can get the instance by Standarduserdefaults static method, and then if you want to save the value to invoke the specific type of method, and in the The types of nsuserdefaults that can be saved here are these types: NSData, NSString, NSNumber, NSDate, Nsarray, nsdictionary, basic data Types

Where NSData is the binary data after the object serialization has been described above, so you can see from here we can also use the Nsuserdefaults to do the object archive and file operation. You can then also store the data collection type, but it is important to note that the collection types that are saved and read are immutable , which is critical if the variable collection type is read and written. The last point is also very simple, is the data stored here is the key is unique, if the use of the same key value, then the value will overwrite the previous value.

Attention:

The immutable logic mentioned above is that the collection of operations is immutable when saved to a file, but we can do this:


In fact, this operation is not an error, but it is important to note that the saved to the file and read from the file object is immutable. Here we print the type of the object read:


Is the __nscfarray type, this type is actually the Nsarray at runtime the actual operation object, he is the C language implementation, is the Nsarray class cluster. Or we do this to look at the effect, is to add elements to the data to see how:


When running, you will find a crash:


Also confirms that the return is a immutable type.


Here we save a Nsinteger value to Key=age, and this nsuserdefaults saved data file, in the above analysis of the sandbox data directory structure has been introduced, is saved in the library/preferences/directory, The file name is: The package name of the app. plist


This saved format is a plist file, similar to the property file in Java, we can open the view information directly using Xcode:


In fact, inside can be seen is a dictionary structure to save data.


The third type: plist file storage

This way is not really a separate storage, but because he is more special to come up with the introduction of, this plist file format is very common in iOS stored in a file format, For example, the above Nsuserdefaults way to save the final file format is plist, here we will describe the iOS collection type data can be saved directly to this file.


See this operation is not very simple, each collection type has a corresponding read-write file method, we have to save the data in the documents/demo.plist, we can go to see the effect:


It is a nsarray format when you see it stored here. It looks more concise and convenient.


The fourth type: Database Storage method

About the database This storage method is very practical, both Android and iOS are using the same database SQLite, but android in use when using the Java language, in fact, the core of the operation is in the native layer, So for iOS, you can directly manipulate the database with C code. At the same time you can see the efficiency and the use of the better than Android.

Most of the previous large databases or SQLite databases used in Android are divided into the following steps: Open the database, establish a connection, execute the corresponding database statement, and finally get the data and results we want. Finally, remember to close the database. general operation of the database is to delete and change the four operations. In Android we need to get the database object by opening the database and then execute the SQL statement with the database object. In iOS It's also a similar operation, in order to see the effect, here's the demo: Create a table, insert data, query data. For deletion and update operations, the same is not a separate description.

1. Open the Database

When you open the database, you need to pass in a database file name path, and then call the sqlite3_open function to open the database:


The logic here is similar to Android, if the first discovery data file does not exist on the creation, if there is not created, see this function has two parameters: one is the database file name path, one is open after the database pointer. A status code is also returned.

Note: Here we will find the importance of pointers in C, and see here A pointer to the effect that a function returns multiple values. So the pointer is the soul of the C language. Very powerful!

Regarding the return value of the status code, we also need to determine whether it is successful, that is, the database is successfully opened, using the SQLITE_OK constant to make judgments.



2. Create a table

After successfully opening the database, you can use the database pointer to execute the corresponding SQL statement, of course, the first statement here must be to create a table, about the SQL syntax is not much introduced. Here, the sqlite3_exec is used to execute the SQL statement, it needs to pass in the database pointer, and in order to be able to return more information, such as here also want to get execution error message, again used to the pointer, define an error message string pointer passed in. Also returns the execution state of an SQL statement, which requires a successful judgment.


Note that the syntax for creating a table here makes a decision as to whether the table already exists in logic.


3. Inserting data

Now that you've created the person data table, here's a look at how to insert a piece of data, insert the data still using the SQL statement, which is the same way as in Android, using placeholders to populate the field values:


First call the sqlite3_prepare_v2 function to check the syntax for any errors, and get a sqlite3_stmt type pointer for the subsequent placeholder complement value. If you find that the syntax is not a problem, continue calling the Sqlite_bind_text and sqlite_bind_int functions to populate the placeholder values, where each data type has a corresponding function. Once the padding is complete, call the sqlite2_step function to execute the statement, and there is still a return value to determine whether the operation completed successfully.


4. Query data

The above has been successfully inserted into a data, the following continue to check out this data, the operation is very simple, create a query statement, there is no condition to judge, if there is a corresponding conditional placeholder, of course, placeholder fill operation and similar to the above:


After you create the query statement, you still use sqlite3_prepare_v2 for syntax checking, and if successful, start using the sqlite3_step function to iterate through the contents of each line. Then start reading each line of content information inside the loop, using the sqlite3_column_text and sqlite3_column_int functions to get the value of the corresponding field, here is obtained by using the index of the field instead of the name of the field. Index subscript starting from 0 .


5. Close the database

After each operation of the database must remember to close the database, close the database is very simple, call the sqlite3_close function.



Here we introduced the storage of the database, you can see the pure C language call, the efficiency is very high. Of course, we also see the above steps to operate the database is a bit cumbersome, so the following article will detail a database operating framework, then the framework will be used instead of this purebred mode of operation.

Note: when it comes to database operations in iOS there is also a very important point of knowledge is CoreData, which is a wrapper between the database and the object, similar to Hibernate's ORM approach, which corresponds to a table in a class and database, When manipulating objects, you can manipulate the corresponding tabular data in the database. Because it is very large, and many inquiries about the iOS old driver's experience is that the function is too large, in the project is generally not how to use, so this article also do not do too much introduction, if you really want to use the words, in going to see should not be a problem.


Iv. Review of Knowledge

The above has already introduced the main four kinds of data storage in iOS, at the beginning also introduced the sandbox mechanism and the sandbox directory structure knowledge in iOS, here is a detailed summary as a review:

First, the application of the sandbox directory structure knowledge

The main directory of the program is obtained through Nshomedirectory (), with three subdirectories: Documents, Library, tmp.

1. There are caches and preferences directories under the library, including:

1>caches: Saves data that needs to be persisted when the app runs, and itunes syncs the device without backing up the directory. Non-critical data that is typically stored in large volumes and does not require backup.

2>preferences: Save all your app's preferences, and the iOS settings (settings) app will find the app's settings in that directory. When itunes syncs the device, it backs up the directory, and the nsuserdefaults stored here is stored in the plist file.

2. Documents: Saves data that needs to be persisted when the app runs, and it backs up the directory when itunes synchronizes the device. For example, the game app saves the game archive in that directory, where we see the database files, plist files, and archive files that are stored in this directory.

3. tmp: Save the temporary data required for the application to run, and then delete the corresponding files from the directory when you have finished using them. When the app is not running, the system may also purge files in that directory. itunes does not back up the directory when syncing the device.


Second, archive the solution storage mode

This is very similar to object serialization in Android, where a nscoding protocol must be implemented for classes that need to archive the files. Then the method of encoding and decoding can be implemented. From this perspective, he is more like the parcel class operation in Android.


Third, Nsuserdefaults storage mode

This is the easiest way to operate, and the sharedpreferences in Android is very similar, but a lot simpler, you can save many types of values, here are a few things to note:

1, when saving the collection type data, the operation is the immutable type collection

2, the same key corresponding to the value of the former will be covered by the latter

3, can save the value of the NSData type, here is equivalent to the object archive and file operation.


IV. plist file Storage method

This way in fact is not counted as a kind of storage, but he is more special so he introduced it alone, he is used to save the collection type of data, the operation is very simple.


Five, the database storage mode

This approach is probably the most important and the most complex of all storage methods, because we have to write SQL statements, but also to save the contents of the specified class into the database to write a big push code, but the operation is not complex is the code may write a bit more, this is similar to Android, Unless you use a third-party framework in thin operations. Data operation we only need to follow a few steps, start to open the database, set up tables, additions and deletions, and finally after the completion of the operation remember to close the database.


Project Download: http://download.csdn.net/detail/jiangwei0910410003/9671504


v. Summary

This article mainly introduces an important module in iOS is the way data is stored, and the only way to store it in Android is that there is no SD card in iOS, the other is similar, but in the course of operation will find more simple than Android operation, after understanding the data storage, This is followed by a multi-threaded knowledge point, which is getting closer to our goal of manually writing applications. Keep working on it! Remember to order a big praise!


Click here for more information:

Focus on the public, the latest technology dry real-time push


Coding Beautiful Technology Circle sweep into my "tech circle" World

Sweep and make a small series
please specify when adding: "Code Beautiful" Thank you very much!

iOS Rampage---How data is stored in iOS app analytics

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.