In the daily development of NSString, Nsdictionary, Nsarray, NSData, nsnumber these basic classes of data persistence, you can use the method of the attribute list persisted to the. plist file. But some of our custom classes, the way the property list is not available, is the time to Nskeyedarchiver. Take the person class that we wrote earlier as an example to see how nskeyedarchiver.
Person class
//////////////////. h////////////////#import <foundation/foundation.h> ; @interface person:nsobject<nscoding> @property (nonatomic,copy) nsstring *name; @property (nonatomic,assign) int age; @property (nonatomic,copy) nsstring *sex;-(void) printinfo; @end//////////////////. M////////////////#import "Person.h" @implementation person@synthesize name = _name,sex = _sex; @synthesize age = _age;//Write to file-(void) Encodewithcoder :(Nscoder *) encoder{[encoder encodeInt:self.age forkey:@ "age"]; [Encoder encodeObject:self.name forkey:@ "name"]; [Encoder encodeObject:self.sex forkey:@ "Sex"];} Read from file-(ID) Initwithcoder: (Nscoder *) decoder{self.age = [Decoder decodeintforkey:@ "age"]; Self.name = [Decoder decodeobjectforkey:@ "name"]; Self.sex = [Decoder decodeobjectforkey:@ "sex"]; return self;} -(void) Printinfo {NSLog @ "My name is:%@ I am a%@%@ this year, Self.name,self.age,self.sex,nsstringfromclass ([self class]);} @end
Test in APPDELEGATE.M
#import "AppDelegate.h" #import "Person.h" @interface appdelegate () @end @implementation appdelegate-(BOOL) application :(uiapplication *) application didfinishlaunchingwithoptions: (Nsdictionary *) launchoptions {person *person = [[[ Person Alloc] init] autorelease]; Person.age =; Person.sex = @ "male"; Person.name = @ "Superdo.horse"; Get the path to document nsstring *documents = [Nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES) lastobject]; NSString *path = [Documents stringbyappendingpathcomponent:@ "person.archiver"];//extension can be customized [nskeyedarchiver Archiverootobject:person Tofile:path]; Person *person2 = [Nskeyedunarchiver Unarchiveobjectwithfile:path]; [Person2 Printinfo]; return YES;} @end
Printing results:
2015-07-05 22:37:48.876 attendance[80142:2069100] My name is:superdo.horse year old I am a man person
This site article is for baby bus SD. Team Original, reproduced must be clearly noted: (the author's official website: Baby bus )
Reprinted from "Baby bus Superdo Team" original link: http://www.cnblogs.com/superdo/p/4623177.html
[Objective-c] 011_ data Persistence _nskeyedarchiver