Objective C Basic Custom Object Archiving Detailed Explanation and Simple Example

  • 2021-12-11 19:13:59
  • OfStack

To archive custom objects, you must implement NSCoding protocol

NSCoding protocol has two methods, encodeWithCoder method encodes the attribute data of the object, and initWithCoder decodes the archive data to initialize the object.

Example 1

. h header file


 #import <Foundation/Foundation.h>
 @interface user : NSObject <NSCoding>
 @property(nonatomic,retain)NSString *name;
 @property(nonatomic,retain)NSString *email;
 @property(nonatomic,retain)NSString *pwd;
 @property(nonatomic,assign)int age;
 @end

. m implementation file


#import "user.h"
#define AGE @"age"
#define NAME @"name"
#define EMAIL @"email"
#define PASSWORD @"password"
@implementation user
// Encode attributes 
- (void)encodeWithCoder:(NSCoder *)aCoder
{
  [aCoder encodeInt:_age forKey:@"age"];
  [aCoder encodeObject:_name forKey:AGE];
  [aCoder encodeObject:_email forKey:EMAIL];
  [aCoder encodeObject:_pwd forKey:PASSWORD];
}
// Decoding attributes 
- (id)initWithCoder:(NSCoder *)aDecoder
{
  self=[super init];
  if(self)
  {
    self.age=[aDecoderdecodeIntForKey:AGE];
    self.name=[aDecoderdecodeObjectForKey:NAME];
    self.email=[aDecoderdecodeObjectForKey:EMAIL];
    self.pwd=[aDecoderdecodeObjectForKey:PASSWORD];
  }
  return self;
}
-(void)dealloc
{
  [_name release];
  [_email release];
  [_pwd release];
  [super dealloc];
}
@end

Call of main function


  user *userObj=[[user alloc] init];
  userObj.age=33;
  userObj.email=@"adfdadf@qq.com";
  userObj.pwd=@"212212";
  userObj.name=@"ricard";
  NSString *path=[NSHomeDirectory() stringByAppendingPathComponent:@"Desktop/custom.text"];
  BOOL succ=[NSKeyedArchiver archiveRootObject:userObj toFile:path];
  if (succ) {
     NSLog(@"Hello, World!");
     user *usertemp=[NSKeyedUnarchiver unarchiveObjectWithFile:path];
  }

Thank you for reading, hope to help everyone, thank you for your support to this site!


Related articles: