문제

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