比如我们要存储一个Student对象,那么Student类必须遵循NSCoding协议,然后实现NSCoding中得两个方法。
@interface Student : NSObject  <NSCoding>然后再.m文件中实现encodeWithCoder:(存)和initWithCoder:(读)方法,这样就告诉了程序这个对象应该怎么存,要存那些属性,以及需要怎么读!
/**
 *  将某个对象写入文件时会调用
 *  在这个方法中说清楚哪些属性需要存储
 */
- (void)encodeWithCoder:(NSCoder *)encoder
{
    [encoder encodeObject:self.no forKey:@"no"];
    [encoder encodeInt:self.age forKey:@"age"];
    [encoder encodeDouble:self.height forKey:@"height"];
}/**
 *  从文件中解析对象时会调用
 *  在这个方法中说清楚哪些属性需要存储
 */
- (id)initWithCoder:(NSCoder *)decoder
{
    if (self = [super init]) {
        // 读取文件的内容
        self.no = [decoder decodeObjectForKey:@"no"];
        self.age = [decoder decodeIntForKey:@"age"];
        self.height = [decoder decodeDoubleForKey:@"height"];
    }
    return self;
}控制器中得读写方法。
- (IBAction)save {
    // 1.新的模型对象
    Student *stu = [[Student alloc] init];
    stu.no = @"42343254";
    stu.age = 20;
    stu.height = 1.55;
    // 2.归档模型对象
    // 2.1.获得Documents的全路径
    NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    // 2.2.获得文件的全路径
    NSString *path = [doc stringByAppendingPathComponent:@"stu.data"];
    // 2.3.将对象归档
    [NSKeyedArchiver archiveRootObject:stu toFile:path];
}反归档(读取)
- (IBAction)read {
    // 1.获得Documents的全路径
    NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    // 2.获得文件的全路径
    NSString *path = [doc stringByAppendingPathComponent:@"stu.data"];
    // 3.从文件中读取MJStudent对象
    Student *stu = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
}原文:http://blog.csdn.net/ttf1993/article/details/45153545