iOS - 如何使用存档保存和读取文件?

时间:2012-11-09 03:47:25

标签: objective-c ios file nskeyedarchiver archiving

我是Xcode的新手,我真的需要帮助。

我正在尝试使用存档来保存包含项目数组的文件,并尝试将其读取并放入表格视图中。

问题是,当我关闭应用程序然后再次启动它时,当我将数据保存到文件中时,它会覆盖现有文件并且所有存储的数据都会消失。

我正在使用此方法将数据存储在文件中:

-(id)init
{

    if(self = [super init])
    {
        _appSupportPath = [NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES)lastObject];

        if (!_appSupportPath)
            return nil;

        _repositoryPath = [_appSupportPath stringByAppendingPathComponent:FILE_NAME];

        if (_data == nil)
            _data = [[NSMutableDictionary alloc] init];
    }
    return self;
}

-(void)saveToFile
{

    dispatch_queue_t writeQueue = dispatch_queue_create("MyApp:file:write", NULL);

    NSMutableDictionary *localData = [NSMutableDictionary dictionaryWithDictionary:_data];

    dispatch_async(writeQueue, ^{
        NSFileManager *fileManager = [NSFileManager defaultManager];
        if(![fileManager fileExistsAtPath:_appSupportPath])
            [fileManager createDirectoryAtPath:_appSupportPath withIntermediateDirectories:YES attributes:nil error:NULL];
        [NSKeyedArchiver archiveRootObject:localData toFile:_repositoryPath];
    });

}

任何帮助?

如果有更好/更简单的方式存储我不知道的文件,请告诉我。

提前致谢

1 个答案:

答案 0 :(得分:0)

您正确保存。 在init中启动时阅读:

_data = [[NSKeyedUnarchiver unarchiveObjectWithFile:_repositoryPath] retain];

if (_data == nil)
    _data = [[NSMutableDictionary alloc] init];