Pergunta

I'm having an issue with NSKeyedArchiver which has been puzzling me for quite a while now and can't seem to pinpoint the error.

I have a mutable array consisting of Objects of the Class "Device". In my appDelegate I keep a mutableArray of Devices and I have the following three functions:

- (void) loadDataFromDisk {
    self.devices = [NSKeyedUnarchiver unarchiveObjectWithFile: self.docPath];
    NSLog(@"Unarchiving");
}

- (void) saveDataToDisk {
    NSLog(@"Archiving");
    [NSKeyedArchiver archiveRootObject: self.devices toFile: self.docPath];
}

- (BOOL) createDataPath {
    if (docPath == nil) {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
        NSString *docsDir = [paths objectAtIndex:0];
        self.docPath = [docsDir stringByAppendingPathComponent: @"devices.dat"];
        NSLog(@"Creating path");
    }

    NSLog(@"Checking path");

    NSError *error;
    BOOL success = [[NSFileManager defaultManager] createDirectoryAtPath: docPath withIntermediateDirectories: YES attributes: nil error:&error];
    if (!success) {
        NSLog(@"Error creating data path: %@", [error localizedDescription]);
    }
    return success;
}

I keep getting an empty mutableArray from the unarchiving process. I'm using ARC, not sure if that has anything to do with it.

Foi útil?

Solução

SO apparently, what I didn't know was that you have to save your root object, in this case an array, to an NSMutableDictionnary first.

NSMutableDictionary *rootObject;
rootObject = [NSMutableDictionary dictionary];

[rootObject setValue: self.devices forKey: @"devices"];

And then save the rootObject with the NSKeyedArchiver. Weird, hadn't seen this in any of the tutorials.

So you end up with the following functions for loading and saving the data to the NSKeyedArchiver.

- (void) loadArrayFromArchiver {
    NSMutableDictionary *rootObject = [NSKeyedUnarchiver unarchiveObjectWithFile: [self getDataPath]];

    if ([rootObject valueForKey: @"devices"]) {
        self.devices = [rootObject valueForKey: @"devices"];
    }

    NSLog(@"Unarchiving");
}

- (void) saveArrayToArchiver {
    NSLog(@"Archiving");

    NSMutableDictionary *rootObject = [NSMutableDictionary dictionary];

    [rootObject setValue: self.devices forKey: @"devices"];

    [NSKeyedArchiver archiveRootObject: rootObject toFile: [self getDataPath]];
}

- (NSString *) getDataPath {
    self.path = @"~/data";
    path = [path stringByExpandingTildeInPath];
    NSLog(@"Creating path");
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top