使用NSCoder保存自己的类

Ste*_*tef 4 iphone objective-c save nscoder

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

我有一个类RSHighscoreList

@interface RSHighscoreList : NSObject {
    NSMutableArray *list;
}
Run Code Online (Sandbox Code Playgroud)

其中包含列表中RSHighscore的对象

@interface RSHighscore : NSObject {
    NSString *playerName;
    NSInteger points;
}
Run Code Online (Sandbox Code Playgroud)

当我尝试将所有文​​件存储到文件中时

- (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"];
}
Run Code Online (Sandbox Code Playgroud)

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

-[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,即使它是'包裹'.有没有人有个好主意?

out*_*tis 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];
}
...
Run Code Online (Sandbox Code Playgroud)

如果将基类RSHighscore更改为其他类,则可能需要NSObject-initWithCoder:方法更改为调用[super initWithCoder:decoder]而不是[super init].另外,添加<NSCoding>到NSObject的和改变RSHighscore-initWithCoder:现在.

@interface NSObject (NSCoding)
-(id)initWithCoder:(NSCoder*)decoder;
-(void)encodeWithCoder:(NSCoder*)encoder;
@end

@implementation NSObject (NSCoding)
-(id)initWithCoder:(NSCoder*)decoder {
    return [self init];
}
-(void)encodeWithCoder:(NSCoder*)encoder {}
@end

@implementation RSHighscore
-(id)initWithCoder:(NSCoder *)decoder {
    if ((self=[super initWithCoder:decoder])) {
        playerName = [[decoder decodeObjectForKey:kPlayerName] retain];
        points = [decoder decodeIntegerForKey:kPoints];
    }
    return self;
}
...
Run Code Online (Sandbox Code Playgroud)