File Access in iOS

Source: Internet
Author: User

I am developing a notepad, in a way to solve storage problems, how to solve storage problems, storage of several ideas, with file storage, with SQLite storage, with iOS Corecode

Reference: http://www.2cto.com/kf/201503/383775.html

http://blog.csdn.net/enuola/article/details/8076221#

Http://www.cnblogs.com/kenshincui/p/3885689.html#archiver

What is the first question? Get the sandbox path to store data by writing files

The iphone sandbox model has four folders, what is the location of the permanent data store, and what is the simple way to get the path to the emulator.

Documents,tmp,app,library.

(Nshomedirectory ()),

The manually saved files are in the documents file.

Nsuserdefaults saved files in the TMP folder

1. Documents directory: You should write all the de application data files to this directory. This directory is used to store user data or other information that should be backed up regularly.

2. Appname.app directory: This is the application's package directory, which contains the application itself. Because the application must be signed, you cannot modify the contents of this directory at run time, which may cause the application to fail to start.

3. Library directory: There are two sub-directories under this directory: Caches and Preferences
Preferences directory: Contains the application's preferences file. Instead of creating a preference file directly, you should use the Nsuserdefaults class to get and set your application's preferences.
Caches directory: Used to hold application-specific support files, saving the information that is needed during application startup.

4. tmp directory: This directory is used to store temporary files, saving information that is not needed during the application restart.

Several ways to get the contents of the iphone Sandbox (sandbox):

Get the Sandbox home directory path NSString *homedir = Nshomedirectory ();//Get the Documents directory path Nsarray *paths = Nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES); NSString *docdir = [Paths objectatindex:0];//get caches directory path Nsarray *paths = Nssearchpathfordirectoriesindomains ( Nscachesdirectory, Nsuserdomainmask, YES); NSString *cachesdir = [Paths objectatindex:0];//get tmp directory path nsstring *tmpdir =  nstemporarydirectory ();
What is the second question to save? The common ways to access files in iOS are:

1, directly write the way of the file, you can store the object has NSString, Nsarray, Nsdictionary, NSData, NSNumber, the data are all stored in a property list file (*.plist file).

2, Nsueserdefaults (preferences), used to store application settings information, files placed in the Perference directory.

3, archive operation (Nskeyedarchiver), different from the previous two, it can put the custom object in the file.

First, get the sandbox path and store the data by writing the file

#import "ViewController.h" @interface Viewcontroller () @end @implementationviewcontroller-(void) Viewdidload {[Super    Viewdidload];    Do any additional setup after loading the view,typically from a nib. [Self mainoperation];}    -(void) mainoperation{//Get the Cache folder path in Sandbox//method one//sandbox home directory NSString *homepath = Nshomedirectory ();        Stitching path NSString *path = [HomePath stringbyappendingpathcomponent:@ "library/caches"]; Method two//the first parameter target folder directory (Nscachesdirectory find cache folder), the second parameter is to find the directory of the domain (Nsuserdomainmask to find in the user directory), the third parameter is the result of whether the home directory is expanded, 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 a destination folder has only one directory.    NSString *cachepath = [arr lastobject];   or//NSString *cachepath = [arr objectatindex:0];    /**//Get the document folder in the sandbox or the TMP folder path can use the above two methods//tmp folder path can be directly obtained nsstring *tmppath = Nstemporarydirectory (); NSLog (@ "%@", Tmppath), **///stitching path (target path), this time if this lotheve.plist file does not exist under the directory, this directory actuallyis not there.    NSString *filepath = [CachePath stringbyappendingpathcomponent:@ "Tese.plist"];        NSLog (@ "%@", FilePath);    Create data nsdictionary *content = @{@ "Dictionary data Test 1": @ "1", @ "Dictionary data Test 2": @ "2", @ "Dictionary data Test": @ "3"};       Save the data to a file in the destination path (this time if the file does not exist in the path will be created automatically)//write the file with the WriteToFile method will overwrite the original contents [content Writetofile:filepath Atomically:yes];    Read the data (read the contents of the file in a dictionary) nsdictionary *dic = [Nsdictionary Dictionarywithcontentsoffile:filepath]; NSLog (@ "%@", DIC);} @end
Second, using Nsueserdefaults (preferences) to achieve data storage

Each app has a nsuesrdefaults instance that can store app configuration information and user information, such as saving user names, passwords, font size, automatic login, and so on. The data is automatically saved in the sandbox's libarary/preferences directory. Similarly, the method can only access data of the NSString, Nsarray, Nsdictionary, NSData, and NSNumber types.

Attention!

Nsueserdefaults can only store immutable objects.

code example:

#import "LXXViewController.h" @interface Lxxviewcontroller () @end @implementationlxxviewcontroller-(void) viewdidload{    [Super Viewdidload];    Self.title = @ "Nsuserdefaults Demo";} 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, Nsuserdefaults to save the data in the preferences directory    [userdefaults setobject:@ "Lotheve" forkey:@ "name"];    [Userdefaults setobject:@ "Nsuserdefaults" forkey:@ "demo"];    Save (synchronize) the 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 data-(ibaction) GetData: (ID) sender{    //Get Nsuserdefaults object    nsuserdefaults *userdefaults = [ Nsuserdefaults Standarduserdefaults];    Read Data    nsstring *name  = [userdefaults objectforkey:@ "name"];    NSString *demo = [Userdefaults objectforkey:@ "Demo"];    Print Data    NSLog (@ "name =%@ Demo =%@", Name,demo);} @end

  

Third, Nskeyedarchiver (archive operation)

The main benefit of storing data using archive operations is that nskeyedarchiver can store custom objects, unlike the previous two methods, which store only a few commonly used data types.

code example:

It is important to note that the object classes that need to be saved must refer to the Nscoding protocol and implement

Let's take a look at how the custom object is archived, which says that if you want to archive a custom object, this object must implement the Nscoding protocol, where two of the methods must be implemented:

-(void) Encodewithcoder: (Nscoder *) Acoder; The message receiver is encoded by a given archiver;

-(ID) Initwithcoder: (Nscoder *) Adecoder; Returns an initialization object from the data of a given unarchiver;

Person.h

  person.h//  foundationframework////  Created by Kenshin Cui on 14-2-16.//  Copyright (c) 2014 Kenshin Cui. All rights reserved.//#import <Foundation/Foundation.h> @interface person:nsobject<nscoding> @property ( nonatomic,copy) NSString *name; @property (nonatomic,assign) int age; @property (nonatomic,assign) Float height;@ Property (nonatomic,assign) NSDate *birthday; @end

  

Person.m

person.m//foundationframework////Created by Kenshin Cui on 14-2-16.//Copyright (c) 2014 Kenshin Cui. All rights reserved.//#import "Person.h" @implementation Person#pragma Mark decoding-(ID) Initwithcoder: (Nscoder *) adecoder{N    SLog (@ "decode ...");        if (Self=[super init]) {self.name=[adecoder decodeobjectforkey:@ "name"];        Self.age=[adecoder decodeint64forkey:@ "age"];        Self.height=[adecoder decodefloatforkey:@ "Heiht"];    Self.birthday=[adecoder decodeobjectforkey:@ "Birthday"]; } return self;}    #pragma mark code-(void) Encodewithcoder: (Nscoder *) acoder{NSLog (@ "encode ...");    [Acoder encodeobject:_name forkey:@ "name"];    [Acoder encodeint64:_age forkey:@ "age"];    [Acoder encodefloat:_height forkey:@ "height"]; [Acoder encodeobject:_birthday forkey:@ "Birthday"];}    #pragma mark rewrite description-(NSString *) description{nsdateformatter *formater1=[[nsdateformatter Alloc]init];    [email protected] "YYYY-MM-DD"; return [NSString stringwithformat:@] Name=%@,age=%i,height=%.2f,birthday=%@ ", _name,_age,_height,[formater1 Stringfromdate:_birthday];} @end

  

Main.m

  main.m//  foundationframework////  Created by Kenshin Cui on 14-2-16.//  Copyright (c) 2014 Kenshin Cui. All rights reserved.//#import <Foundation/Foundation.h> #import "Person.h" int main (int argc,char *argv[]) {    / /Archive person    *person1=[[person Alloc]init];    [Email protected] "Kenshin";    person1.age=28;    person1.height=1.72;    NSDateFormatter *formater1=[[nsdateformatter Alloc]init];    [Email protected] "YYYY-MM-DD";    Person1.birthday=[formater1 datefromstring:@ "1986-08-08"];        NSString *[email protected] "/users/kenshincui/desktop/person1.arc";        [Nskeyedarchiver Archiverootobject:person1 tofile:path1];    Solution Person    *person2= [Nskeyedunarchiver unarchiveobjectwithfile:path1];    NSLog (@ "%@", Person2);    /* Results:     name=kenshin,age=28,height=0.00,birthday=1986-08-08     */        return 0;}

  

  

File Access in iOS

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.