One of the forms of iOS save files is the Nskeyedarchiver, Nskeyedunarchiver archive:
The following is an example of a to-do lists software, Checklistitem is a project (data model) that contains a string text and a bool tag checked,items is the nsmutablearray of the View controller, Contains multiple checklistitem that are saved to the. plist file as a whole when the data is saved, and read the same.
1. First implement the Protocol <nscoding> in the. h file of the data model, for example:
@interface Checklistitem:nsobject <NSCoding>
2. Add the Encode and decode methods (called when Nscoder Archive and reconcile files)
-(void) Encodewithcoder: (Nscoder *) Acoder
{
[Acoder encodeObject:self.text forkey:@ "text"];
[Acoder encodeBool:self.checked forkey:@ "checked"];
}
-(ID) Initwithcoder: (Nscoder *) Adecoder
{
if (self = [super init])
{
Self.text = [Adecoder decodeobjectforkey:@ "text"];
self.checked = [Adecoder decodeboolforkey:@ "checked"];
}
return self;
}
3. Get the app sandbox document path and saved file names
-(NSString *) documentsdirectory
{
Nsarray *paths = Nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES);
NSString *documentsdirectory = [Paths firstobject];
return documentsdirectory;
}
-(NSString *) DataFilePath
{
return [[Self documentsdirectory] stringbyappendingpathcomponent:@ "checklists.plist"];
}
4. How to save and read. plist files in the view controller
-(void) Savechecklistitems
{
Nsmutabledata *data = [[Nsmutabledata alloc]init];
Nskeyedarchiver *archiver = [[Nskeyedarchiver alloc]initforwritingwithmutabledata:data];
[Archiver encodeobject:_items forkey:@ "Checklistitems"];
[Archiver finishencoding];
[Data writetofile:[self DataFilePath] atomically:yes];
}
-(void) Loadchecklistitems
{
NSString *path = [self datafilepath];
if ([[[Nsfilemanager Defaultmanager] Fileexistsatpath:path])
{
NSData *data = [[NSData alloc] initwithcontentsoffile:path];
Nskeyedunarchiver *unarchiver = [[Nskeyedunarchiver alloc] initforreadingwithdata:data];
_items = [Unarchiver decodeobjectforkey:@ "Checklistitems"];
[Unarchiver finishdecoding];
}
Else
{
_items = [[Nsmutablearray alloc]initwithcapacity:20];
}
}
5. Read the. plist file (if present) when the view is storyboard from the document.
-(ID) Initwithcoder: (Nscoder *) Adecoder
{
if (self = [super Initwithcoder:adecoder])
{
[Self loadchecklistitems];
}
return self;
}
6. Call the Save data method in the action method where you want to save the data (add, delete, modify an item)
[Self savechecklistitems];
iOS learning Nskeyedarchiver, Nskeyedunarchiver archive