To save data permanently, you can use the plist file. When you exit the program, write the data to the plist file and use the writetofile: atomically: method.
Classes with this method are:
NSArrayNSMutableArrayNSDictionaryNSMutableDictionaryNSDataNSMutableDataNSStringNSMutableStringNSNumberNSDate
For example, if our data is stored in an nsarray object array, run the following command to save the data:
[array writeToFile:filePath atomically:YES];
The filepath is the complete path of a plist file in the sandbox.
However, there are limitations in using plist files. For example, it is difficult to store an image in plist.
In this small example, we will save the data through archiving. When running the program, check whether the archive file exists. If yes, read the data from the archive file on the interface. If the archive file does not exist, use the default settings. When the program is closed, the data is stored in the archive file, so that the last setting is displayed when the program is run next time.
1. Run xcode 4.3 to create a new single view application named archiving test:
Then add the two images to the project.
2. design the interface first:
Click viewcontroller. XIB to add the control to it:
Create an outlet ing and action ing for the control in viewcontroller. H. Specifically, create an outlet ing for all textfield, imageview, uislider control, and uiswitch controls to create action ing for the button:
3. Create a new class to store our data:
On the menu bar, select File-New-file ..., In the displayed window, select objective-C class:
Click Next, enter the class name archivingdata, and select "super class" as "nsobject:
Click Next, select the location and group, and click Create to create the class.
4. Open archivingdata. h and add attributes and protocols to it:
#import <Foundation/Foundation.h>@interface ArchivingData : NSObject <NSCoding, NSCopying>@property (copy, nonatomic) UIImage *image;@property (copy, nonatomic) NSString *name;@property (copy, nonatomic) NSString *gender;@property (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:kImageKey]; 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] init]; 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 added several attributes that correspond one to one with the control created above. Then several protocol methods are implemented, which are used for encoding, decoding, and replication.
6. Open viewcontroller. h and add attributes and methods to it:
@property (copy, nonatomic) NSString *archivingFilePath;- (void)applicationWillResignActive:(NSNotification *)notification;
7. Open viewcontroller. M and add the 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]; // do any 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 file exists, read the content and display nsdata * Data = [[nsmutabledata alloc] initwithcontentsoffile: Self. archivingfilepath]; optional * unarchiver = [nskeyedunarchiver alloc] failed: Data]; archivingdata * archivingdata = [unarchiver decodeobjectforkey: Failed]; [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 imageviewto 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]; [[nsicationcenter center defacenter center] addobserver: Self selector: @ selector (applicationwillresignactive :) 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] failed: Data]; [archiver encodeobject: archivingdata forkey: karchivingdatakey]; [archiver finishencoding]; [data writetofile: Self. archivingfilepath atomically: Yes];}
8. Finally, to enable the keyboard to be closed, we need to add and disable the keyboard. For details, refer to step 2nd in iOS development 4: Disable the keyboard.
9. Run the program
The figure on the left is as follows:
We add some data, change the Avatar, and then adjust the silder and switch, such as the Right.
Then, run the program in the background by creating the home on the simulator.
In this case, check the sandbox of the program and you can see that the file archivingfile appears in the program's documents directory:
Run the program after using xcode. When the program runs for the second time, it is displayed on the left. This shows that data is stored permanently.
From: http://my.oschina.net/plumsoft/blog/57180