質問

I'm creating a class which will store the statistics for my game. I'd like to store each round score into a mutable array which can be persisted and written to file.

I'm using the NSCoding protocol and implementing the encodeWithCoder and initWithCoder Methods.

#define masteredComponentsKey @"masteredComponents"
#define scoresKey   @"scores"
-(void)encodeWithCoder:(NSCoder *)encoder
{
    [encoder encodeObject:_masteredComponents forKey:masteredComponentsKey];
    [encoder encodeObject:_scores forKey:scoresKey];

}

-(id)initWithCoder:(NSCoder *)decoder
{
    self = [super init];
    if (self)
    {
        _masteredComponents = [decoder decodeObjectForKey:masteredComponentsKey];
        _scores = [decoder decodeObjectForKey:scoresKey];
    }
    return self;
}

Since arrays are pointers to objects in Objective-C, I figure my scores need to be an Object-Wrapped integer such as an NSNumber or NSValue. However, these Objects don't implement NSCoding Protocol.

So what's the best way to persist a bunch of numbers using NSCoding?

----This is my first StackOverflow post so please excuse any unusual decorum----

役に立ちましたか?

解決

NSValue and NSNumber implement NSCoding protocol so you can use them ..

NSValue implementes NSSecureCoding which is inherited from NSCoding, look at the Reference

So you can use them:

[encoder encodeObject:@(_scores) forKey:scoresKey];
...
_scores = [[decoder decodeObjectForKey:scoresKey] intValue];
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top