Pergunta

So I have an array with some custom classes:

NSMutableArray With Games (FirstViewcontroller) -Game with Dices (Game.m) -- Dices With Options (Dices.m)

In each custom class i've setter the encode and decode up:

-(void)encodeWithCoder:(NSCoder *)aCoder{
    [aCoder encodeObject:[self _gameNaam] forKey:@"_gameNaam"];
}

-(id)initWithCoder:(NSCoder *)aDecoder{
    if (!(self = [super init]))
        return nil;
    [self set_gameNaam:[aDecoder decodeObjectForKey:@"_gameNaam"]];

    return self;
}

And in the first view controller I am handeling the loading and saving. But the decoder always returns null of no array. So nothing inside of it. Here is my code:

- (void) saveToFile{
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *bestand = [path stringByAppendingPathComponent:@"data.kets"];

    if ([NSKeyedArchiver archiveRootObject:[self dobbelArray] toFile:bestand])
        NSLog(@"Did it!!");
}

- (void) loadFromFile{

    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *bestand = [path stringByAppendingPathComponent:@"data.kets"];

    if ([[NSFileManager defaultManager] fileExistsAtPath:bestand]){
        if ([NSKeyedUnarchiver unarchiveObjectWithFile:bestand])
            NSLog(@"Did it!!");
    }
}

-(void)encodeWithCoder:(NSCoder *)aCoder{
    [aCoder encodeObject:[self dobbelArray] forKey:@"dobbelArray"];
}

-(id)initWithCoder:(NSCoder *)aDecoder{
    if (!(self = [super initWithCoder:aDecoder]))
        return nil;

    [self setDobbelArray:[aDecoder decodeObjectForKey:@"dobbelArray"]];

    return self;
}

Not sure of what i'm doing wrong? The loading is called in the - (void)viewDidLoad FirstViewController. After the [NSMutableArray new]; of my array. Saving is done when going back grom an UnwindSegue from my addViewController.

Any idea's?

Kind Regards

Foi útil?

Solução

unarchiveObjectWithFile: returns the unarchived object for you to use. At the moment you just check if it is nil (with your if statement) and then it gets destroyed (deallocated because you don't use it, assuming you're using ARC).

So, get the object returned by unarchiveObjectWithFile: and set it to your property.

Not sure what you're trying to do with NSCoding on the view controller, but it may well not do what you're looking for.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top