There are five ways to cache data in iOS locally

Source: Internet
Author: User
Tags list of attributes sqlite sqlite database tmp folder

Objective

There are five ways to locally cache data in iOS:

1. Direct writing file: The objects that can be stored are nsstring, Nsarray, Nsdictionary, NSData, NSNumber, all of which are stored in a property list file (*.plist file).

2.NSUserDefaults (preferences) for storing application settings information and files in the Perference directory.

3. Archive operation (Nskeyedarchiver), different from the first two, it can store custom objects in the file.

4.coredata:coredata, an integrated database of Apple's official iOS5, uses an ORM (Object Relational Mapping) object-relational mapping technique to convert objects to data and store them in a local database. CoreData in order to improve efficiency, and even store data in different databases, and in the use of local data in memory to make access faster. We can choose the CoreData data storage mode, including SQLite, XML and other formats. But it is the coredata is completely object-oriented, and its execution efficiency is not comparable to the native database. In addition, CoreData has the data validation, undo and other functions, in the functional is the most of several persistence schemes.

5.fmdb:fmdb is the iOS platform's SQLite database framework, Fmdb in OC to encapsulate the SQLite C language API, use more object-oriented, save a lot of trouble, redundant C language code, compared with Apple's core data framework, More lightweight and flexible, providing a multi-threaded and secure database operation method to effectively prevent data clutter. Way One: write files directly

Get cached folder path in sandbox

Method One

Sandbox home Directory

NSString *homepath = Nshomedirectory ();

Stitching paths

NSString *path = [HomePath stringbyappendingpathcomponent:@ "library/caches"];

Method Two

The first parameter target folder directory (Nscachesdirectory lookup cache folder), the second parameter is the lookup directory domain (Nsuserdomainmask to find in the user directory), the third parameter is the main directory in the result is expanded, and not expanded is displayed as ~

Nsarray *arr = Nssearchpathfordirectoriesindomains (Nscachesdirectory, Nsuserdomainmask, YES);

Although the method returns an array, there is only one element in the array because one destination folder has only one directory.

NSString *cachepath = [arr lastobject];

Or

NSString *cachepath = [arr objectatindex:0];

/**

The previous two methods can be used to get the document folder in the sandbox or the TMP folder path

The TMP folder path can be obtained directly

NSString *tmppath = Nstemporarydirectory ();

NSLog (@ "%@", Tmppath);

**/

Stitching path (target path), this directory does not actually exist if the Lotheve.plist file is not present in the directory.

NSString *filepath = [CachePath stringbyappendingpathcomponent:@ "Tese.plist"];

NSLog (@ "%@", FilePath);

Creating data

Nsdictionary *content = @{@ "Dictionary data Test 1": @ "1", @ "Dictionary data Test 2": @ "2", @ "Dictionary data Test": @ "3"};

Save data to a file in the destination path (this time if the file does not exist in the path will be created automatically)

Writing a file with the WriteToFile method overwrites the original content.

[Content Writetofile:filepath Atomically:yes];

Read the data (read the contents of the file in a dictionary)

Nsdictionary *dic = [Nsdictionary Dictionarywithcontentsoffile:filepath];

NSLog (@ "%@", DIC);

More lotheve.plist files in the Library/caches directory in the sandbox:

File contents:

How to get the emulator sandbox path:

Print the log, copy the path to open the Mac Finder, click on the upper left corner menu to go to the folder and paste the path up.

NSString *path = [Nssearchpathfordirectoriesindomains (Nsdocumentdirectory,nsuserdomainmask,yes) objectAtIndex:0];

NSLog (@ "%@", Path); mode two: Nsuserdefaults (preferences)

Each application has a Nsuesrdefaults instance that allows you to store application configuration information and user information, such as saving user names, passwords, font sizes, automatically logging in, and so on. The data is automatically saved in the Libarary/preferences directory of the Sandbox. Similarly, this method can only access data from NSString, Nsarray, Nsdictionary, NSData, and NSNumber types.

A list of properties is a lightweight way of storing plaintext, with several storage formats, the most common format being XML. When we create a new project, Xcode automatically generates a portion of the system settings that the Info.plist file uses to store the project. Plist can only be read with an array (Nsarray) or a dictionary (nsdictionary), because the list of attributes itself is not encrypted, so security can almost be said to be zero. Because the list of properties is normally used to store small and unimportant data.

After the program is started, the system automatically creates a Nsuserdefaults single Instance object that we can get to store a small amount of data, which stores the output in a file in the. plist format. The advantage is that a dictionary-like assignment is easy, but the disadvantage is that you cannot store custom data.

code example:

Click button to save data

-(Ibaction) SaveData: (ID) Sender {

Get Nsuserdefaults Object

Nsuserdefaults *userdefaults = [Nsuserdefaults standarduserdefaults];

Save data, do not need to set the road strength, nsuserdefaults to save the data in the preferences directory

[Userdefaults setobject:@ "Lotheve" forkey:@ "name"];

[Userdefaults setobject:@ "Nsuserdefaults" forkey:@ "demo"];

Save (sync) data immediately (if you do not write this, you will automatically save the data in the Preferences directory at some point in the future)

[Userdefaults Synchronize];

NSLog (@ "Data saved");

}

Click button to read the data

-(Ibaction) GetData: (ID) sender

{

Get Nsuserdefaults Object

Nsuserdefaults *userdefaults = [Nsuserdefaults standarduserdefaults];

Reading data

NSString *name = [userdefaults objectforkey:@ "name"];

NSString *demo = [Userdefaults objectforkey:@ "Demo"];

Print data

NSLog (@ "name =%@ Demo =%@", Name,demo);

}

After you click "Save Data", view the Libarary/preferences directory in the sandbox:

The data is written to disk in plist format. Click to view data:

Mode three: Nskeyedarchiver (archive operation)

In contrast to the list of attributes, as a durable solution for lightweight storage, data archiving is encrypted and data is converted into binary data as it is archived, so security is much higher than the list of attributes. In addition to archiving, we can write complex objects to a file and write the object to disk in the same way, regardless of how many objects are added.

Use Nskeyedarchiver to serialize your custom data and save it in a sandbox directory. The premise of using this kind of archiving is to keep the data model of the storage in compliance with the Nscoding protocol and implement its two protocol methods. (Of course, if you are able to comply with the Nssecurecoding protocol for more secure storage, this is the new feature after IOS6)

The primary benefit of storing data using an archive operation is that, unlike the previous two methods, you can store only a few data types that are commonly used, and Nskeyedarchiver stores custom objects.

code example:

First, create a class that inherits NSObject, which adheres to the Nscoding protocol

TestPerson.h

@interface Testperson:nsobject

@property (nonatomic, copy) NSString *name;

@property (nonatomic, assign) Nsinteger age;

@property (nonatomic, copy) NSString *sex;

@property (nonatomic, strong) Nsarray *familymumbers;

@end

Testperson.m

#import "TestPerson.h"

@interface Testperson ()

@end

@implementationTestPerson

-(void) viewdidload

{

[Super Viewdidload];

}

#pragma mark-nscoding protocol method (must be implemented)

This method is called when an archive operation is made

In this method, write clearly which properties of the object you want to store

-(void) Encodewithcoder: (Nscoder *) Acoder

{

NSLog (@ "called the Encodewithcoder Method");

[Acoder encodeobject:_name forkey:@ "name"];

[Acoder encodeinteger:_age forkey:@ "age"];

[Acoder encodeobject:_sex forkey:@ "Sex"];

Related Article

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.