I have this class with an NSMutableArray
of custom Cocos2d objects implementing the NSCoding
protocol.
@interface PlayerData : NSObject <NSCoding> {
}
@property (readwrite, nonatomic) NSMutableArray *levelsStars; //Where levelsStars is filled with objects conforming to the NSCoding protocol.
The objects are of type LevelData
, which inherits from CCNode
(a Cocos2d class) and conforms to the NSCoding
protocol.
@interface LevelData : CCNode <NSCoding>
Here is the implementation of the protocol in PlayerData
. In order to encode and decode the NSMutableArray
of custom Cocos2d objects, which conform to NSCoding
objects:
-(void) encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeObject:[NSKeyedArchiver archivedDataWithRootObject:levelsStars] forKey:kLevelsStars];
}
-(id) initWithCoder:(NSCoder *)aDecoder
{
self = [super init];
if (self) {
//Reading arrays:
NSData * dataRepresentingLevelStars = [aDecoder decodeObjectForKey:kLevelsStars];
if (dataRepresentingLevelStars!=nil) {
NSArray * oldSavedArray = [NSKeyedUnarchiver unarchiveObjectWithData:dataRepresentingLevelStars];
if (dataRepresentingLevelStars!=nil) {
levelsStars = [NSMutableArray arrayWithArray:oldSavedArray];
}
else
{
levelsStars = [[NSMutableArray array] initWithCapacity:10];
}
}
}
return self;
}
Is this approach correct? I based it on this question / answer.
EDIT: I thought I will add some more details on my use case
My users can choose among different characters, each characters corresponds to a PlayerData object which I plan to store in a different file appending the user's game center id (id-character1.archive, id-character2.archive etc..).
I do save progress of the characters in the object (e.g. score, life) including the NSMutableArray custom array of Cocos2d-objects (in my real case I do have 5 different arrays containing 20/30 objects each).