2

我是第一次实现 iOS 状态保存和恢复,所以这个问题对于更有经验的人来说可能很明显!

我有一个故事板,其中包含通往各种场景的多条路径。例如,从场景 A 开始,用户可以到场景 B,然后到场景 C,或者用户可以直接到场景 C。

在 View Controller A 中创建一个“大”NSDictionary,然后将其传递给 View Controller B,然后通过 prepareForSegue 方法传递给 View Controller C(或直接传递给 C)。

我相信我能够在 View Controller A 中恢复 NSDictionary,但是如何为 View Controller B 和/或 C 获取它而不是制作额外的副本?

4

2 回答 2

1

这里不应该担心内存。假设它看起来像这样:

- (void) prepareForSegue .... {
  nextViewController.dictionary = self.dictionary;    
}

我避免了细节,但重点是这是传递对 NSDictionary 的引用,而不是复制整个字典。这意味着您的所有视图控制器实际上将共享完全相同的字典。

所以他们不应该担心拥有一本大字典的副本。尽管您应该知道,如果 View Controller B 确实更改了字典,这些更改将在所有其他视图控制器中受到影响。

希望这个答案。

于 2014-04-29T17:23:54.577 回答
0

因为视图控制器是按顺序恢复的,从根开始,我发现按照我的要求做实际上非常简单。首先,在 Navigation 控制器中获取当前视图控制器的索引。由此,找出之前出现的视图控制器。(如果我的 Storyboard 更复杂,我可以在前一个视图控制器上使用“isKindOfClass”来确定如何在其中获取 NSDictionary。)

例如:

- (void)decodeRestorableStateWithCoder:(NSCoder *)coder
{
    [super decodeRestorableStateWithCoder:coder];

    // get current index of views in navigation controller
    int index = [[self navigationController].viewControllers indexOfObject:self];

    if (index == 1) {
        ViewControllerA *view = [[self navigationController].viewControllers objectAtIndex:index - 1];
        self.dict = view.someDict;
    }
    else if (index == 2) {
        ViewControllerB *view = [[self navigationController].viewControllers objectAtIndex:index - 1];
        self.dict = view.arrayOfDict[0];
    }
}
于 2014-05-01T20:37:54.020 回答