【问题标题】:iOS NSKeyedArchiver unarchive returns empty arrayiOS NSKeyedArchiver unarchive 返回空数组
【发布时间】:2013-09-23 08:11:23
【问题描述】:

我遇到了 NSKeyedArchiver 的问题,这让我困惑了很长时间,似乎无法查明错误。

我有一个由“设备”类的对象组成的可变数组。 在我的 appDelegate 中,我保留了一个 mutableArray 的设备,并且具有以下三个功能:

- (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;
}

我不断从取消归档过程中得到一个空的 mutableArray。我正在使用 ARC,不确定是否与此有关。

【问题讨论】:

    标签: ios nskeyedarchiver


    【解决方案1】:

    显然,我不知道您必须先将根对象(在本例中为数组)保存到 NSMutableDictionnary。

    NSMutableDictionary *rootObject;
    rootObject = [NSMutableDictionary dictionary];
    
    [rootObject setValue: self.devices forKey: @"devices"];
    

    然后用 NSKeyedArchiver 保存 rootObject。奇怪,在任何教程中都没有看到这个。

    因此,您最终会获得以下用于将数据加载和保存到 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");
    }
    

    【讨论】:

    • 嗨,谢谢分享,我也有同样的问题,但我不明白答案:( ...根对象是一个字典,你把数组放入其中,作为键对吗?那么当您取消归档时,您会将其取消归档到字典中?还是到数组中?
    • 我包含了全部功能,希望对您有所帮助。
    • 非常感谢!*竖起大拇指*
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-28
    • 2014-10-07
    相关资源
    最近更新 更多