【问题标题】:iOS - Lifecycle using NSNotificationCenteriOS - 使用 NSNotificationCenter 的生命周期
【发布时间】:2017-06-22 15:36:55
【问题描述】:

我有一个具有底部选项卡布局的 iOS (Objective C) 应用程序。 我的以下设置运行良好,除非尚未加载第二个选项卡。我的第一个视图控制器(第一个选项卡)从第二个视图控制器调用了一个观察到的方法:

VC1:

-(void) callmethodVC2 {

[[NSNotificationCenter defaultCenter]postNotificationName:@"MYFUNC" object:nil];
//switch to 2nd Tab
self.tabBarController.selectedIndex = 1;

}

VC2: 在viewDidLoad()我注册:

[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(loadSomething) name:@"MYFUNC" object:nil];

稍后在 VC2 中我实现了观察方法:

-(void) loadSomething {...}

所以 VC1 通过 NotifacationCenter 调用该方法 -> 标签栏按预期切换,该方法效果很好,但 如果我访问了第二个标签 之前。

我猜是当我在加载 viewDidLoad 方法之前访问第二个 VC 并且有注册的观察方法!因此,如果我在没有调用 viewDidLoad 方法之前没有访问 VC2,也没有注册观察者方法。

如何在我的第一个 VC 中“预加载”第二个 VC,这是推送第二个 VC 的正确方法吗?又是如何做到的?

【问题讨论】:

    标签: ios uiviewcontroller nsnotificationcenter


    【解决方案1】:

    你是对的,viewDidLoad 只被调用一次,第一次在屏幕上显示视图。您应该在初始化程序中注册观察者,而不是在 viewDidLoad 中注册。

    如果你使用故事板:

    - (instancetype)initWithCoder:(NSCoder *)aDecoder
    {
        self = [super initWithCoder:aDecoder];
        if (self) {
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadSomething) name:@"MYFUNC" object:nil];
        }
        return self;
    }
    

    如果您的视图控制器以编程方式实例化:

    - (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
    {
        self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
        if (self) {
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadSomething) name:@"MYFUNC" object:nil];
        }
        return self;
    }
    

    【讨论】:

    • 谢谢 - 这就是我需要知道的!
    【解决方案2】:

    我认为您只需要预加载视图控制器即可解决您的问题。我为您找到了与我之前使用的相同的solution

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-28
      • 1970-01-01
      • 2020-12-27
      • 1970-01-01
      • 2013-06-06
      • 2011-07-30
      相关资源
      最近更新 更多