In normal use, we usually need to archive custom objects. to archive custom objects, we need to implement the NSCoding protocol.
The NSCoding protocol has two methods. The encodeWithCoder method encodes the attribute data of an object.
The initWithCoder method decodes archive data to initialize the object.
After implementing the NSCoding protocol, you can use NSKeyedArchiver for archiving.
The example code is as follows:
Person. h header file code:
#import
@interface Person : NSObject
@property(nonatomic,copy)NSString *name;@property(nonatomic,copy)NSString *email;@property(nonatomic,copy)NSString *password;@property(nonatomic,assign)int age;@end
Person. m implementation code:
# Import "Person. h "# define AGE @" age "# define NAME @" name "# define EMAIL @" email "# define PASSWORD @" password "@ implementation Person // encode Object Attributes method-(void) encodeWithCoder :( NSCoder *) acder {[acder encodeInt: _ age forKey: AGE]; [acder encodeObject: _ name forKey: NAME]; [acder encodeObject: _ email forKey: EMAIL]; [ACO der encodeObject: _ password forKey: PASSWORD];} // decode object attributes-(id) initWithCoder :( NSCoder *) aDec Oder {self = [super init]; if (self! = Nil) {_ age = [aDecoder decodeIntForKey: AGE]; _ name = [[aDecoder decodeObjectForKey: NAME] copy]; _ email = [[aDecoder decodeObjectForKey: EMAIL] copy]; _ password = [[aDecoder decodeObjectForKey: PASSWORD] copy];} return self;}-(void) dealloc {[_ name release]; [_ email release]; [_ password release]; [super dealloc];}
Main. m function code:
# Import
# Import "Person. h "int main (int argc, const char * argv []) {@ autoreleasepool {Person * person = [[Person alloc] init]; person. name = @ "jack"; person. age = 20; person. email = @ "jack@163.com"; person. password = @ "12345"; NSString * homePath = NSHomeDirectory (); NSString * srcPath = [homePath stringByAppendingPathComponent: @ "Desktop/person. archiver "]; BOOL success = [NSKeyedArchiver archiveRootObject: person toFile: srcPath]; if (success) {NSLog (@" the custom object has been archived successfully. ");} // restore Data Person * result = [NSKeyedUnarchiver unarchiveObjectWithFile: srcPath]; NSLog (@" name = % @ ", result. name); NSLog (@ "age = % d", result. age); NSLog (@ "email = % @", result. email); NSLog (@ "password = % @", result. password);} return 0 ;}
Run: