0

我有一个类对象,例如;

BookEntity.h

    import <Cocoa/Cocoa.h>

    @interface BookEntity : NSObject<NSCoding> {

        NSString *name;
        NSString *surname;
        NSString *email;
    }
@property(copy) NSString *name,*surname,*email;
@end

BookEntity.m

#import "BookEntity.h"


@implementation BookEntity
@synthesize name,surname,email;
- (void) encodeWithCoder: (NSCoder *)coder
{

    [coder encodeObject: self forKey:@"appEntity"];

}   
- (id) initWithCoder: (NSCoder *)coder
{
    if (self = [super init])
    {

        self = [coder decodeObjectForKey:@"appEntity"];

    }
    return self;
}

我为这个类分配了一些值,

BookEntity *entity = [[BookEntity alloc] init];
entity.name = @"Stewie";
entity.surname = @"Griffin";
entity.email = @"sg@example.com";

所以我想使用 NSKeyedArchiver 存储这个类并使用 NSKeyedUnarchiver 恢复。

我写入文件,但是当我检索此文件时,实体具有任何价值。

做这个的最好方式是什么?

谢谢。

4

1 回答 1

2

您对NSCoding协议的使用不正确。您不应该归档对象本身,而应该归档对象的属性,然后再取消归档。你会这样做:

- (void) encodeWithCoder: (NSCoder *)coder
{
    [coder encodeObject:self.name forKey:@"name"];
    [coder encodeObject:self.surname forKey:@"surname"];
    [coder encodeObject:self.email forKey:@"email"];
}   
- (id) initWithCoder: (NSCoder *)coder
{
    if (self = [super init])
    {
        self.name = [coder decodeObjectForKey:@"name"];
        self.surname = [coder decodeObjectForKey:@"surname"];
        self.email = [coder decodeObjectForKey:@"email"];
    }
    return self;
}
于 2011-03-29T17:04:29.483 回答