使用NSCoder保存自己的类

时间:2010-11-30 18:31:30

标签: iphone objective-c save nscoder

我正在尝试将一些自定义类/数据存储到我的iPhone / iPad应用程序中的文件中。

我有一个类RSHighscoreList

@interface RSHighscoreList : NSObject {
    NSMutableArray *list;
}

包含列表中的RSHighscore对象

@interface RSHighscore : NSObject {
    NSString *playerName;
    NSInteger points;
}

当我尝试将所有内容存储到文件

- (void)writeDataStore {
    RSDataStore *tmpStore = [[RSDataStore alloc] init];
    _tmpStore.highscorelist = self.highscorelist.list;
    NSMutableData *data = [[NSMutableData alloc] init];
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];

    [archiver encodeObject:tmpStore forKey:kDataKey];
    [archiver finishEncoding];
    [data writeToFile:[self dataFilePath] atomically:YES];

    [archiver release];
    [data release];
}

@interface RSDataStore : NSObject <NSCoding, NSCopying> {
    NSMutableArray *highscorelist; 
}

- (void)encodeWithCoder:(NSCoder *)encoder {
    [encoder encodeObject:highscorelist forKey:@"Highscorelist"];
}

该应用程序将崩溃并显示错误消息

-[RSHighscore encodeWithCoder:]: unrecognized selector sent to instance 0x573cc20
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[RSHighscore encodeWithCoder:]: unrecognized selector sent to instance 0x573cc20'

我想知道为什么错误会告诉我RSHighscore,即使它是'包裹'。有没有人有个好主意?

2 个答案:

答案 0 :(得分:10)

RSDataStore有一个-encodeWithCoder:方法,但是(根据错误消息)RSHighscore没有。您需要为要序列化的每个类实现NSCoding协议。

@implementation RSHighscore
static NSString *const kPlayerName = @"PlayerName";
static NSString *const kPoints = @"Points";

-(id)initWithCoder:(NSCoder *)decoder {
    if ((self=[super init])) {
        playerName = [[decoder decodeObjectForKey:kPlayerName] retain];
        points = [decoder decodeIntegerForKey:kPoints];
    }
    return self;
}
-(void)encodeWithCoder:(NSCoder *)encoder {
    [encoder encodeObject:playerName forKey:kPlayerName];
    [encoder encodeInt:points forKey:kPoints];
}
...

如果RSHighscore的基类更改为NSObject以外的其他内容,则可能需要将-initWithCoder:方法更改为调用[super initWithCoder:decoder]而不是{{1} }}。或者,将[super init]添加到NSObject并立即更改<NSCoding>的{​​{1}}。

RSHighscore

答案 1 :(得分:4)

您要编码的类或initWithCoder应符合<NSCoding>协议 所以你应该在界面中添加它,否则运行时确实不会识别选择器,因为它是<NSCoding>协议的一部分