http://blog.sina.com.cn/s/blog_7b9d64af01019kk5.html

Object-C中我们可以对 NSDate, NSNumber, NSString, NSArray, or NSDictionary对象进行“编码/解码”的操作。


但是,当我们对自己定义的对象进行“编码/解码”操作时,却需要实现NSCoding协议的相关方法来告诉程序如何来“编码/解码”我们自己的对象!
NSCoding协议的方法:
- (void)encodeWithCoder:(NSCoder *)aCoder;
- (id)initWithCoder:(NSCoder *)aDecoder;


那么,我们就对类实现“编码/解码”协议:
在AddressCard.h中,申明实现NSCoding协议:
@interface AddressCard : NSObject<NSCopying,NSCoding>


在AddressCard.m中,实现NSCoding协议的编码/解码 方法:

#pragma mark- NSCoding
 - (void)encodeWithCoder:(NSCoder *)aCoder{
     [aCoder encodeObject:self.name forKey:@"AddressCard_name"];
     [aCoder encodeObject:self.email forKey:@"AddressCard_email"];
     [aCoder encodeInt32:self.salary forKey:@"AddressCard_salary"];


 }
 - (id)initWithCoder:(NSCoder *)aDecoder{
     _name=[[aDecoder decodeObjectForKey:@"AddressCard_name"] retain];
     _email=[[aDecoder decodeObjectForKey:@"AddressCard_email"] retain];
     _salary=[aDecoder decodeInt32ForKey:@"AddressCard_salary"];
     return self;


 }

这样,我们就能够归档自己定义的类对象。

NSString *filePhyName=[filePath stringByAppendingPathComponent:@"ObjectFile"];
     BOOL isSuccess=NO;
     isSuccess= [NSKeyedArchiver archiveRootObject:objArray toFile:filePhyName];
     if (isSuccess) {
         NSLog(@"Success");
     }else{
         NSLog(@"False");
     }
     
     // 反归档
     NSMutableArray *myObj=[NSKeyedUnarchiver unarchiveObjectWithFile:filePhyName];
     for (AddressCard *theCard in myObj) {
         [theCard print];
     }





从输出可以看到,归档成功!
归档需要注意的是:
1.同一个对象属性,编码/解码的key要相同!
2.每一种基本数据类型,都有一个相应的编码/解码方法。
如:encodeObject方法与decodeObjectForKey方法,是成对出现的。
3.如果一个自定义的类A,作为另一个自定义类B的一个属性存在;那么,如果要对B进行归档,那么,B要实现NSCoding协议。并且,A也要实现NSCoding协议。


希望对您有所帮助