【问题标题】:iOS - How to Save to and Read from file using Archiving?iOS - 如何使用存档保存和读取文件?
【发布时间】:2012-11-09 03:47:24
【问题描述】:

我是 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];
    });

}

有什么帮助吗?

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

提前致谢

【问题讨论】:

    标签: objective-c ios file nskeyedarchiver archiving


    【解决方案1】:

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

    _data = [[NSKeyedUnarchiver unarchiveObjectWithFile:_repositoryPath] retain];
    
    if (_data == nil)
        _data = [[NSMutableDictionary alloc] init];
    

    【讨论】:

    • 哦,我错过了那行,它开箱即用!谢谢你!
    猜你喜欢
    • 1970-01-01
    • 2015-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多