iOS Development UI Chapter-ios Application Data Storage (archive)

Source: Internet
Author: User

To permanently save the data, we can of course use the Plist file, and when we exit the program we perform the operation of writing the data to the Plist file, using the writetofile:atomically: method.

The classes that have this method are:

Nsarraynsmutablearraynsdictionarynsmutabledictionarynsdatansmutabledatansstringnsmutablestringnsnumbernsdate

For example, our data is stored in an array of objects in Nsarray and is executed when the data is saved:

[Array Writetofile:filepath atomically:yes];

Where filepath is the full path of a plist file that is placed in the sandbox.

However, there are limitations to using plist files, for example, we are not good at storing a picture in plist.

In this small example, we will save the data by filing. When the program runs, first check the existence of the archive file, if present, read the data from the archive display on the interface, if the archive does not exist, use the default settings. When the program shuts down, the data is stored in the archive so that the last setting is displayed the next time the program is run.

1. Run Xcode 4.3 and create a new single View application, named: Archiving Test:

Then add the two pictures you have prepared to the project.

2, the first interface design:

Click Viewcontroller.xib to add the control to it:

The outlet map and the action map are then established for the control in ViewController.h, with uislider mappings for all TextField, ImageView, Uiswitch controls, and outlet controls. To establish an action map for the button:

3. Create a new class to store our data:

In the menu bar, select File-new-file ... in the open window, select Objective-c Class:

Click Next, enter the class name: Archivingdata, select Super class for NSObject:

Click Next, select the location and group, click Create, complete the creation of the class.

4. Open ArchivingData.h, add attributes to it, and protocol:

#import <Foundation/Foundation.h> @interface archivingdata:nsobject <nscoding, nscopying> @property (copy , nonatomic) UIImage *image, @property (copy, nonatomic) NSString *name; @property (copy, nonatomic) NSString *gender; @prop Erty (copy, nonatomic) NSString *vocation, @property (copy, nonatomic) nsstring *page; @property float Theslider; @property BOOL Isswitchon; @end

5. Open ARCHIVINGDATA.M and add code to it:

5.1 Add code before @implementation:

#define Kimagekey @ "ImageKey" #define Knamekey @ "Namekey" #define Kgenderkey @ "Genderkey" #define Kvocationkey @ " Vocationkey "#define Kpagekey @" Pagekey "#define Kthesliderkey @" Thesliderkey "#define Kisswitchon @" Isswitchonkey "

5.2 Add code after @implementation:

@synthesize image; @synthesize name; @synthesize gender; @synthesize vocation; @synthesize page; @synthesize theslider;@ Synthesize Isswitchon;

5.3 Add code before @end:

 #pragma mark nscoding-(void) Encodewithcoder: (Nscoder *)    Acoder {[Acoder encodeobject:image forkey:kimagekey];    [Acoder Encodeobject:name Forkey:knamekey];    [Acoder Encodeobject:gender Forkey:kgenderkey];    [Acoder encodeobject:vocation Forkey:kvocationkey];    [Acoder encodeobject:page Forkey:kpagekey];    [Acoder Encodefloat:theslider Forkey:kthesliderkey];    [Acoder Encodebool:isswitchon Forkey:kisswitchon]; }-(ID) Initwithcoder: (Nscoder *) Adecoder {if (self = [super init]) {image = [Adecoder decodeobjectforkey:kimag        EKey];        name = [Adecoder Decodeobjectforkey:knamekey];        gender = [Adecoder Decodeobjectforkey:kgenderkey];        Vocation = [Adecoder Decodeobjectforkey:kvocationkey];        page = [Adecoder Decodeobjectforkey:kpagekey];        Theslider = [Adecoder Decodefloatforkey:kthesliderkey];    Isswitchon = [Adecoder Decodeboolforkey:kisswitchon]; } return self;} 

5.4 Add code before @end:

#pragma mark nscoping-(ID) Copywithzone: (Nszone *) zone {    Archivingdata *copy = [[[Self class] allocwithzone:zone] ini T];    Copy.image = Self.image;    Copy.name = [Self.name copywithzone:zone];    Copy.gender = [Self.gender copywithzone:zone];    Copy.vocation = [Self.vocation copywithzone:zone];    Copy.page = [Self.page copywithzone:zone];    Copy.theslider = Self.theslider;    Copy.isswitchon = Self.isswitchon;    return copy;}

In the Archivingdata class, we have added several properties that correspond to the one by one controls created above. Then several protocol methods were implemented, which were used for encoding, decoding and copying.

6. Open ViewController.h and Add properties and methods to it:

@property (copy, nonatomic) NSString *archivingfilepath;-(void) applicationwillresignactive: (Nsnotification *) Notification

7. Open VIEWCONTROLLER.M and Add code:

7.1 Add code after @implementation:

@synthesize Archivingfilepath;

7.2 Add code after #import:

#import "ArchivingData.h" #define Karchivingfilekey @ "Archivingfile" #define Karchivingdatakey @ "Archivingdatakey"

7.3 Add code in the Viewdidload method:

-(void) viewdidload{[Super Viewdidload];    Additional setup after loading the view, typically from a nib.    Nsarray *paths = Nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES);    NSString *documentsdirectory = [Paths objectatindex:0];    Self.archivingfilepath = [Documentsdirectory Stringbyappendingpathcomponent:karchivingfilekey];        Nsfilemanager *filemanager = [Nsfilemanager Defaultmanager]; if ([FileManager FileExistsAtPath:self.archivingFilePath]) {//If the archive exists, it reads the contents, which is displayed on the interface nsdata *data = [NSMU        Tabledata alloc] InitWithContentsOfFile:self.archivingFilePath];        Nskeyedunarchiver *unarchiver = [[Nskeyedunarchiver alloc] initforreadingwithdata:data];        Archivingdata *archivingdata = [Unarchiver Decodeobjectforkey:karchivingdatakey];        [Unarchiver finishdecoding];        Theimageview.image = Archivingdata.image;        Nametextfield.text = Archivingdata.name; Gendertextfield.text = Archivingdata.Gender        Vocationtextfield.text = archivingdata.vocation;        Pagetextfield.text = Archivingdata.page;        Theslider.value = Archivingdata.theslider;    Theswitch.on = Archivingdata.isswitchon;    } else {//If the archive file does not exist, set ImageView to Boy.png theimageview.image = [UIImage imagenamed:@ "Boy.png"];    }//When the program enters the background, write the current settings to the archive file uiapplication *app = [UIApplication sharedapplication]; [[Nsnotificationcenter Defaultcenter] addobserver:self selector: @selector (APPL                                               Icationwillresignactive:) name:uiapplicationwillresignactivenotification Object:app];}

7.4 Find the Switchimage method and add the code:

-(Ibaction) Switchimage: (ID) Sender {    UIImage *image1 = [UIImage imagenamed:@ "Boy.png"];    UIImage *image2 = theimageview.image;    if (![ Image1 Isequal:image2]) {        theimageview.image = image1;    } else {        theimageview.image = [UIImage imagenamed:@] Gemini.png "];    }}

7.5 Add code before @end:

When the program enters the background, save settings-(void) Applicationwillresignactive: (nsnotification *) Notification {    Archivingdata * Archivingdata = [[Archivingdata alloc] init];    Archivingdata.image = Self.theImageView.image;    Archivingdata.name = Self.nameTextField.text;    Archivingdata.gender = Self.genderTextField.text;    Archivingdata.vocation = Self.vocationTextField.text;    Archivingdata.page = Self.pageTextField.text;    Archivingdata.theslider = Theslider.value;    Archivingdata.isswitchon = Theswitch.on;    Nsmutabledata *data = [[Nsmutabledata alloc] init];    Nskeyedarchiver *archiver = [[Nskeyedarchiver alloc] initforwritingwithmutabledata:data];    [Archiver encodeobject:archivingdata Forkey:karchivingdatakey];    [Archiver finishencoding];    [Data WriteToFile:self.archivingFilePath atomically:yes];}

8, finally, in order to make the keyboard can be closed, we also want to add the operation to turn off the keyboard, refer to "iOS Development 4: Turn off the keyboard" in the 2nd step.

9. Running the program

Just run the program as shown in the left image:

We add some data, change the avatar, and then adjust the silder and switch, such as right.

After that, the emulator is built on the home, making the program run in the background.

At this point, look at the sandbox of the program, you can see the program's Documents directory appears under the file Archivingfile:

Then use Xcode to end the run and then run the program. When the program is run for the second time, it shows as left, which means that we implement the persistent storage of the data.

iOS Development UI Chapter-ios Application Data Storage (archive)

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.