实现NSCoding协议可以为NSArchiver提供基础,也可以实现将数据写入plist里的功能

下面来看看怎么实现NSCoding的,其实很简单

有这么一个类

@interface Note : NSObject {
    NSString *title;
    NSString *author;
    BOOL published;
}

@property (nonatomic, copy) NSString *title;
@property (nonatomic, copy) NSString *author;
@property (nonatomic) BOOL published;

@end
#import "Note.h"

@implementation Note

@synthesize title;
@synthesize author;
@synthesize published;

- (void)dealloc {
    [title release];
    [author release];
    [super dealloc];
}

@end
实现NSCoding后:
@interface Note : NSObject <NSCoding> {
    NSString *title;
    NSString *author;
    BOOL published;
}

@property (nonatomic, copy) NSString *title;
@property (nonatomic, copy) NSString *author;
@property (nonatomic) BOOL published;

@end
#import "Note.h"

@implementation Note

@synthesize title;
@synthesize author;
@synthesize published;

- (void)dealloc {
    [title release];
    [author release];
    [super dealloc];
}

- (id)initWithCoder:(NSCoder *)decoder {
    if (self = [super init]) {
        self.title = [decoder decodeObjectForKey:@"title"];
        self.author = [decoder decodeObjectForKey:@"author"];
        self.published = [decoder decodeBoolForKey:@"published"];
    }
    return self;
}

- (void)encodeWithCoder:(NSCoder *)encoder {
    [encoder encodeObject:title forKey:@"time"];
    [encoder encodeObject:author forKey:@"author"];
    [encoder encodeBool:published forKey:@"published"];
}

@end
就是这么简单,形式对了就对了!