SoFunction
Updated on 2025-04-13

Objective-C Basics Detailed explanation and simple examples of custom object archives

To implement the archive of a custom object, the NSCoding protocol must be implemented.

The NSCoding protocol has two methods: the encodeWithCoder method encodes the object's attribute data, and the initWithCoder decodes the archived data to initialize the object.

Example 1

.h header file

 #import <Foundation/>
 @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 ""
#define AGE @"age"
#define NAME @"name"
#define EMAIL @"email"
#define PASSWORD @"password"
@implementation user
//Encoding 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];
}
//Decode the attribute- (id)initWithCoder:(NSCoder *)aDecoder
{
  self=[super init];
  if(self)
  {
    =[aDecoderdecodeIntForKey:AGE];
    =[aDecoderdecodeObjectForKey:NAME];
    =[aDecoderdecodeObjectForKey:EMAIL];
    =[aDecoderdecodeObjectForKey:PASSWORD];
  }
  return self;
}
-(void)dealloc
{
  [_name release];
  [_email release];
  [_pwd release];
  [super dealloc];
}
@end

Calling main function

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

Thank you for reading, I hope it can help you. Thank you for your support for this site!