iOS data local persistence

Source: Internet
Author: User
Tags tmp folder xml attribute

 P1:
There are three main forms of local storage in iOS development
    • XML attribute list (plist) archive
    • Preference (preference setting)
    • Nskeyedarchiver Archive (nscoding)
Apply Sandbox
What is the app sandbox

If you want to store data locally, you need to know what the sandbox is, but it's good to understand that the app Sandbox is the app's folder and is isolated from other file systems. Each iOS app has its own app sandbox, and the app must stay in its sandbox, and other apps won't be able to access the sandbox.
How to get the app sandbox path, you can get the app sandbox path by printing nshomedirectory () to print the path result:


Screen shot 2015-12-03 22.10.07.png


Melody_zhy is a user folder (looks like a booth)
3cec8eeb-c230-44be-93b7-df3b9a120a94 iOS8 each time you run Xcode will generate a different sandbox path, the difference is the last folder name, may be Apple for the sake of security

Application Sandbox structure Analysis

First, let's take a look at what's inside the sandbox.


Screen shot 2015-12-03 22.27.50.png


Here, the Finder's shortcut key shift + COM + G can go to a folder of any path, so we can print the sandbox path and then copy the sandbox path to the finder to go to the path folder and go to the app sandbox. This is a way to delay things! Fortunately there is an app called Simpholders, it can easily access the application of the sandbox path, remember to download Simpholders2 Oh, after the first generation of iOS8 can not be used, the app is easy to understand, the use will be ~
Now let's see what these folders are for in the application sandbox.

    • 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
    • library/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 with large storage volumes and no backup required
    • library/preference : Save all your app's preferences , and the iOS settings (settings) app will find the app's settings in that directory. This directory is backed up when itunes syncs the device
    • tmp : Saves the temporary data required to run the app, and then deletes the corresponding file from the directory when it is finished. When the app is not running, the system may also purge files in that directory. itunes does not back up this directory when syncing the device
common ways to get the sandboxed catalog applied
How to get the sandbox root directory

As we have said above:

NSString *home = NSHomeDirectory();
How to get the Documents folder (3 types)

The First kind (! Stupid! )

// 利用沙盒根目录拼接字符串NSString *homePath = NSHomeDirectory();NSString *docPath = [homePath stringByAppendingString:@"/Documents"];

The Second kind (! Still??! )

// 利用沙盒根目录拼接”Documents”字符串NSString *homePath = NSHomeDirectory();NSString *docPath = [homePath stringByAppendingPathComponent:@"Documents"];

However, this method is not recommended, because it is not possible to change the name of the file in the day of the Big Apple-_-!

The Third Kind (! ~ Recommended ~! )

//nsdocumentdirectory files to find Span class= "Hljs-comment" >//Nsuserdomainmask represents //in iOS, only one directory matches the parameters passed in. So there's only one element in this set nsstring *path =  Nssearchpathfordirectoriesindomains (nsdocumentdirectory, nsuserdomainmask, yes) [0];< Span class= "hljs-built_in" >nsstring *filepath = [path Stringbyappendingpathcomponent:@ " Xxx.plist "];             

Here I come to the details of the Nssearchpathfordirectoriesindomains this method of several parameters:
< #NSSearchPathDirectory directory#> This parameter represents the file to find, which is an enumeration! Enumeration you know, click to see it.
< #NSSearchPathDomainMask domainmask#> This parameter represents the search from the user folder and is also an enumeration!
The last parameter if it is no, the printed path will be this form ~/documents, we will generally use yes, so that we can get the full path string!
The return value of this method is an array, but in iOS, only one directory matches the parameters passed in, so there is only one element in the collection, so we take the first element!

How to get the Library/caches folder (similar to the method above)

Here I only use the third method above! Take note of the first parameter!

NSString *path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];NSString *filePath = [path stringByAppendingPathComponent:@"student.data"];
How to get the TMP folder
NSString *tmp= NSTemporaryDirectory();
How to get the Library/preference folder

Access the settings information in this directory through the Nsuserdefaults class!
!!! The following will be introduced!!!

XML attribute list (plist) archive
plist file

The root type of plist can only be a dictionary (nsdictionary) or an array (Nsarray) so we can only save the array or dictionary to the plist file when we archive it. But NSString can also be saved to the plist file by the archive and it can also be stringwithcontentsoffile, it is saved to the plist when the type is empty, value is valuable!

Archiving of plist files
nsarray *arr = [[NSArray alloc] Initwithobjects:@ "1", @ "2", nil]; //nsdocumentdirectory the file to find //nsuserdomainmask representative from the user folder to find the Span class= "Hljs-comment" >//in iOS, only one directory matches the parameters passed in, so there is only one element in the collection nsstring *path = nssearchpathfordirectoriesindomains (NSDocumentDirectory, Span class= "hljs-built_in" >nsuserdomainmask, yes) [0];nsstring *filepath = [path Stringbyappendingpathcomponent:@ " Xxx.plist "]; [Arr writetofile:filepath atomically:yes];        
plist files
NSString *filePath = [path stringByAppendingPathComponent:@"xxx.plist"];// 解档NSArray *arr = [NSArray arrayWithContentsOfFile:filePath];NSLog(@"%@", arr);
Preference (preference setting)

OC has a nsuserdefaults singleton, which can be used to store user preferences, such as: User name, font size, some user settings, etc., below I use two uiswitch to demonstrate how to save the user settings switch off state

Save User Preferences
// 获取用户偏好设置对象NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];// 保存用户偏好设置[defaults setBool:self.one.isOn forKey:@"one"];[defaults setBool:self.two.isOn forKey:@"two"];// 注意:UserDefaults设置数据时,不是立即写入,而是根据时间戳定时地把缓存中的数据写入本地磁盘。所以调用了set方法之后数据有可能还没有写入磁盘应用程序就终止了。// 出现以上问题,可以通过调用synchornize方法强制写入// 现在这个版本不用写也会马上写入 不过之前的版本不会[defaults synchronize];
Read User Preferences
// 读取用户偏好设置NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; self.one.on = [defaults boolForKey:@"one"];self.two.on = [defaults boolForKey:@"two"];
Nskeyedarchiver Archive (nscoding)

Only classes that comply with the Nscoding protocol can use Nskeyedarchiver to archive and nskeyedunarchiver files, if the object is NSString, Nsdictionary, Nsarray, NSData, NSNumber and other types, can be directly used Nskeyedarchiver Archive and Nskeyedunarchiver solution ~
I'll give you the following. is a student model for archive files, so the model should adhere to the Nscoding protocol

Implement Encodewithcoder and Initwithcoder methods
- (void) Encodewithcoder: ( Nscoder *) Coder{[coder encodeobject:self. Name Forkey:@ "Name"];[ Coder Encodeinteger: Self, AgeForkey:@ "age"];} -(Instancetype) Initwithcoder: (nscoder *) coder{self= [super init];  if (self) {self . Age= [coder Decodeintegerforkey:@ ' age ']; self. Name = [Coder Decodeobjectforkey:@ "name"];} return self ;}                 
Archive
Student *s1 = [[Student alloc] init];s1.name = @"zzz";s1.age = 18;NSString *path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];// 这个文件后缀可以是任意的,只要不与常用文件的后缀重复即可,我喜欢用dataNSString *filePath = [path stringByAppendingPathComponent:@"student.data"];// 归档[NSKeyedArchiver archiveRootObject:s1 toFile:filePath];
Solution file
NSString *path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];NSString *filePath = [path stringByAppendingPathComponent:@"student.data"];// 解档Student *s = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];NSLog(@"%@----%ld", s.name, s.age);

RELATED Links: Summary of local data storage in iOS development

P2:

iOS confidential data is saved with keychain

RELATED links: Saving data in iOS Keychain

What is applied to iOS keychain projects

P3:

RELATED Links: Implementing local caches using ASIHTTPRequest and Asidownloadcache

1, set the global cache
Add a global variable in AppDelegate.h

[Plain]View Plaincopy
    1. @interface Appdelegate:uiresponder
    2. {
    3. Asidownloadcache *mycache;
    4. }
    5. @property (Strong, nonatomic) UIWindow *window;
    6. @property (Nonatomic,retain) Asidownloadcache *mycache;

In APPDELEGATE.M-(BOOL) Application: (UIApplication *) application didfinishlaunchingwithoptions: (NSDictionary *) Add the following code to the Launchoptions method

[Plain]View Plaincopy
    1. Custom Cache
    2. Asidownloadcache *cache = [[Asidownloadcache alloc] init];
    3. Self.mycache = cache;
    4. [Cache release];
    5. Set the cache path
    6. Nsarray *paths = Nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES);
    7. NSString *documentdirectory = [Paths objectatindex:0];
    8. [Self.mycache setstoragepath:[documentdirectory stringbyappendingpathcomponent:@ "resource"];
    9. [Self.mycache Setdefaultcachepolicy:asionlyloadifnotcachedcachepolicy];

Add the following statement to the Dealloc method in APPDELEGATE.M

[Plain]View Plaincopy
    1. [Mycache release];

The declaration of the global variable has been completed so far.

2. Set the cache policy

Set the request storage location where the ASIHTTPRequest requests are implemented, as shown in the code below

[Plain]View Plaincopy
    1. NSString *str = @ "http://....../getPictureNews.aspx";
    2. Nsurl *url = [Nsurl urlwithstring:str];
    3. ASIHTTPRequest *request = [ASIHTTPRequest Requestwithurl:url];
    4. Get Global variables
    5. Appdelegate *appdelegate = [[UIApplication sharedapplication] delegate];
    6. Set Cache mode
    7. [Request SetDownloadCache:appDelegate.myCache];
    8. Set the cache data Storage policy, where the cached data is read if it is not updated or is not networked
    9. [Request Setcachestoragepolicy:asicachepermanentlycachestoragepolicy];
    10. Request.delegate = self;
    11. [Request startasynchronous];

3. Clean up cached data

What I'm using here is to manually clean up the data, add the following code where appropriate, and I'll clean up the cache in the app's setup module:

[Plain]View Plaincopy
    1. Appdelegate *appdelegate = [[UIApplication sharedapplication] delegate];
    2. [Appdelegate.mycache Clearcachedresponsesforstoragepolicy:asicachepermanentlycachestoragepolicy];

This is the asicachepermanentlycachestoragepolicy cache of this storage policy, and if you replace other parameters, you can clean up the cached data for the corresponding storage policy. (Reference: http://zycto.blog.163.com/blog/static/17152400201110221340738/)

iOS data local persistence

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.