【问题标题】:Finding different instances in NSKeyedArchiver在 NSKeyedArchiver 中查找不同的实例
【发布时间】:2013-02-27 01:59:06
【问题描述】:

我目前正在使用这个博客,它使用与 NSKeyedArchiver 一起使用的自定义类。一切似乎都是正确的,但我想知道如何获得“学生”的不同实例。

http://keeptheseinmind.blogspot.com/2011/10/nskeyedarchiver-tutorial.html

在本教程中,每次终止应用程序时都会创建自定义类“students”的新实例。我假设在 NSKeyedArchiver 中有很多这样的“学生”实例,但我只能访问其中一个。

保存到磁盘

- (void)saveDataToDisk {
    NSString *path = @"~/Documents/data";
    path = [path stringByExpandingTildeInPath];

    NSMutableDictionary *rootObject;
    rootObject = [NSMutableDictionary dictionary];

    [rootObject setValue:student forKey:@"student"];

    [NSKeyedArchiver archiveRootObject:rootObject toFile:path];
}

从磁盘加载

- (void)loadDataFromDisk {
    NSString *path = @"~/Documents/data";
    path = [path stringByExpandingTildeInPath];

    NSMutableDictionary *rootObject;
    rootObject = [NSKeyedUnarchiver unarchiveObjectWithFile:path];

    if ([rootObject valueForKey:@"student"]) {
        student = [rootObject valueForKey:@"student"];
    }
}

编辑:

我弄错了,每次实例都相互覆盖,每次应用程序都被终止。有趣...

但是,我的目标仍然是在一个或多个 NSKeyedArchiver 中创建许多“学生”实例。任何想法将不胜感激。

【问题讨论】:

    标签: objective-c memory nsarchiving


    【解决方案1】:

    您可以将NSKeyedArchiver 视为将对象(序列化)保存到磁盘的一种方式。在您的情况下,该对象是一个 NSDictionary,它只有一个键 student(我使用 JSON-ish 表示法来显示数据结构;希望意图很明确):

    "student" : { "studentId" : 25,
                  "studentName" : "John Smith"
                }
    

    正如您所注意到的,每次调用 saveDataToDisk 时,它只是覆盖了单个“学生”键。要拯救多个学生,您可以采取以下几种方法:您的选择将取决于您希望如何读回数据。

    一种选择是存储一个数组,而不是NSDictionary

    "student" : [ { "studentId: 25, "studentName" : "John Smith" },
                  { "studentId: 26, "studentName" : "Jane Doe" } ]
    

    如果您采用这种方法,您需要确保saveDataToDisk 可以访问NSArray 的学生,并将该数组传递给rootObject setValue:

    [rootObject setValue:students forKey:@"students"];
    

    或者,您可以想象只想在字典中添加更多键,每个键代表一个学生:

    "student25" : { "studentId: 25, "studentName" : "John Smith" },
    "student26" : { "studentId: 26, "studentName" : "Jane Doe" }
    

    在这种情况下,您将再次需要确保您的保存函数可以访问一组学生,但这次您将遍历该数组,并使用您构造的自己的键将每个人添加到 rootDictionary通过(例如)将“student”与 studentId 连接起来。

    【讨论】:

    • 我想使用学生数组方法。但是,我想建立加班的学生人数;当我们想要归档它时,它不一定已经准备好。我想先查看archiveData文件中的学生,然后添加学生。我只是尝试通过取消归档(如果文件存在)然后在此之上进行归档来做到这一点,但现在似乎没有任何内容被存储。
    • 但是,根据我的需要,刚刚尝试了新的密钥方法!穆乔·格拉西亚斯! :) 好主意!
    • 并且......在得到它之后,我回到 NSMutableArray 并让它工作:)!首先,我将 NSMutableArray 设置为 rootObject 并使用 addObject 方法。在这种情况下不应该使用任何键。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-12
    • 1970-01-01
    • 1970-01-01
    • 2021-01-17
    • 1970-01-01
    • 2019-03-11
    • 2012-07-12
    相关资源
    最近更新 更多