【问题标题】:Archiving Multiple Objects and Unarchiving them as array of objects in objective C在目标 C 中归档多个对象并将它们作为对象数组取消归档
【发布时间】:2014-05-07 22:27:25
【问题描述】:

我在整个程序中的不同时间调用函数 archiveQueue 来存储 MYJSON 类型的对象,现在我想恢复我迄今为止存储在一个数组中的所有内容。

以下是我用来存储对象的函数:

- (void)archiveQueue:(MYJSON *)msg{

    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:msg];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *file = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"myqueue.txt"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    [fileManager createFileAtPath:file contents:data attributes:nil];
    NSLog(@"ArchiveQueue: file = %@", file);

}

以下是我用来恢复对象的功能。

- (void)restoreQueue {


    NSLog(@"RestoreQueue: Restoring queue from Document Directory.");
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *file = [[paths objectAtIndex:0]  stringByAppendingPathComponent: @"myqueue.txt"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSData *data = [fileManager contentsAtPath:file];


        // How to unarchive that array of objects being stored. 

}

我想知道我应该如何解压缩存储为对象数组的所有内容?

【问题讨论】:

  • 如果你在处理 json 为什么不直接保存为 json?
  • 由于项目的一些要求,我不允许保存为json。
  • 我很困惑。 jsonObject 不是你解压后存储的数据吗?
  • Okie Chuck !对不起,我现在删除了那行。我只想恢复我通过 NSKeyArchiver 存储的所有对象。
  • createFileAtPath:contents:attributes: 将覆盖之前在该位置的所有内容。你总是会得到一个对象。

标签: objective-c nskeyedarchiver nskeyedunarchiver


【解决方案1】:

为了使用 NSKeyedArchiver 保存自定义类,该类需要实现 NSCoding 协议。即使您的类实例作为NSArrayNSDictionary 的成员包含在内,您也需要让它们符合。

使用createFileAtPath:contents:attributes: 将覆盖该文件的内容。

这里有一些选项:

每次归档一组对象。

get an array of all objects
add your new object
write that array to disk

将对象归档到目录中的唯一文件

documents/mySpecialObjects/A.myObject
documents/mySpecialObjects/B.myObject
documents/mySpecialObjects/C.myObject
...

create local NSMutableArray
enumerate all files inside of documents/mySpecialObjects
unarchive each file and add to your array

【讨论】:

  • 但它会创建许多我想附加到现有文件并获取数组中的数据的文件。
  • @NileshAgrawal 再次阅读第一个选项 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-03
相关资源
最近更新 更多