UIViewController生命周期调用与状态恢复相结合 [英] UIViewController lifecycle calls in combination with state restoration

查看:140
本文介绍了UIViewController生命周期调用与状态恢复相结合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在使用iOS 6+和故事板的应用程序中实现状态恢复,但是我在找到防止重量级方法重复调用的方法时遇到了问题。

I'm trying to implement state restoration in an app that uses iOS 6+ and storyboards, but I am having problems finding a way to prevent duplicate calls to heavy methods.

如果我只是启动应用程序,那么我需要在 viewDidLoad 中设置用户界面:

If I simply start the app, then I need to setup the UI in viewDidLoad:

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
}

这在正常的非状态恢复世界中运行良好。现在我添加了状态恢复,在恢复一些属性后,我需要用这些属性更新UI:

This works fine in a normal, non-state-restoration world. Now I've added state restoration and after restoring some properties I need to update the UI with those properties:

- (void)decodeRestorableStateWithCoder:(NSCoder *)coder {
    [super decodeRestorableStateWithCoder:coder];
    // restore properties and stuff
    // [...]
    [self setupUI];
}

那么现在发生的是首先 setupUI 方法从 viewDidLoad 调用,然后再从 decodeRestorableStateWithCoder:调用。我没有看到一个我可以覆盖的方法,它总是被称为最后一个。

So what happens now is that first the setupUI method is called from viewDidLoad, and then again from decodeRestorableStateWithCoder:. I don't see a method that I can override that's always called last.

这是方法调用的正常顺序:

This is the normal order of method calls:


  • awakeFromNib

  • viewDidLoad

  • viewWillAppear

  • viewDidAppear

  • awakeFromNib
  • viewDidLoad
  • viewWillAppear
  • viewDidAppear

使用状态恢复时,这称为:

When using state restoration, this is called:


  • awakeFromNib

  • viewDidLoad

  • decodeRestorableStateWithCoder

  • viewWillAppear

  • viewDidAppear

  • awakeFromNib
  • viewDidLoad
  • decodeRestorableStateWithCoder
  • viewWillAppear
  • viewDidAppear

我无法在<$中拨打 setupUI c $ c> viewWillAppear 因为每当你回到视图时它也会被执行。

I can't place the call to setupUI in viewWillAppear because then it would also be executed every time you native back to a view.

如果 decodeRestorableStateWithCoder 被称为BEFORE viewDidLoad 因为那时你可以使用恢复的属性。可悲的是,不是这样,所以......当我知道我需要在 viewDidLoad 中进行工作? > decodeRestorableStateWithCoder 之后?

It would be much handier if decodeRestorableStateWithCoder was called BEFORE viewDidLoad because then you could use restored properties. Sadly that not the case, so... how can I prevent doing the work in viewDidLoad when I know that I need to do it all over again in decodeRestorableStateWithCoder right after?

推荐答案

@property (nonatomic) BOOL firstLoad;

- (void)viewDidLoad {
    [super viewDidLoad];
    self.firstLoad = YES;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    if (self.firstLoad) {
        [self setupUI];
        self.firstLoad = NO;
    }
}

感谢@calvinBhai的建议。

Thanks to @calvinBhai for the suggestion.

这篇关于UIViewController生命周期调用与状态恢复相结合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆