无法在 AppDelegate 中初始化委托,但在 class 方法中它可以工作

Can't initializing a delegate in the AppDelegate but inside a class method it works

我正在尝试在 didFinishLaunchingWithOptions 方法内的 AppDelegate 中初始化委托 (MyDelegate),如下所示:

UIStoryboard *myStoryboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
[[someClassName instance] setMyDelegate:[myStoryboard instantiateViewControllerWithIdentifier:@"someVcName"]];

在调试时,所有的调用都表现良好,但是在上述调用之后returns到AppDelegate时,MyDelegate为nil。

有趣的是,当我尝试在我编写的 class 方法中设置委托时,它起作用了——与上面的代码完全相同。

为什么初始化在 AppDelegate 中不起作用,而它在 class 方法中起作用?

谢谢。

编辑:

基本上 @Leo 解决了问题,但解决方案非常简单,因为我使用的是 Storyboard 然后是第一个 ViewController自动启动(假设您分配了入口点箭头图标):

解决方法:

[[someClassName instance] setMyDelegate:[self.window rootViewController]];

关于方法 instantiateViewControllerWithIdentifier

来自文档

This method creates a new instance of the specified view controller each time you call it.

因此,在 didFinishLaunchingWithOptions 中,您创建了一个本地 viewController 实例。

并且,方法完成后将被释放。