简体   繁体   English

无法在AppDelegate中初始化委托,但可以在类方法中初始化

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

I am trying to initialize a delegate ( MyDelegate ) in the AppDelegate inside the didFinishLaunchingWithOptions method as follows: 我正在尝试在didFinishLaunchingWithOptions方法内的didFinishLaunchingWithOptions初始化委托( MyDelegate ),如下所示:

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

While debugging, all the calls perform well but when it returns to the AppDelegate after the above calls, MyDelegate is nil. 在调试时,所有调用均执行良好,但是在上述调用之后返回到AppDelegate时,MyDelegate为零。

What is interesting is that when I try to set the delegate inside a class method I wrote, it works - the exact same code above. 有趣的是,当我尝试在编写的类方法中设置委托时,它可以工作-与上面完全相同的代码。

Why the initializing doesn't work in the AppDelegate while it works in the class method ? 为什么初始化在类方法中起作用却无法在AppDelegate中起作用?

Thanks. 谢谢。

EDIT : 编辑

Basically @Leo solved the problem but the solution was really straightforward since I was using Storyboard then the first ViewController is automatically initiated (assuming you assigned the entry point arrow icon): 基本上, @ Leo解决了问题,但是解决方案非常简单,因为我使用的是Storyboard,然后自动启动了第一个ViewController(假设您已分配了入口点箭头图标):

The solution: 解决方案:

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

About method instantiateViewControllerWithIdentifier 关于方法instantiateViewControllerWithIdentifier

From the document 来自文件

This method creates a new instance of the specified view controller each time you call it. 每次调用时,此方法都会创建指定视图控制器的新实例。

So,in didFinishLaunchingWithOptions ,you create a local viewController instance. 因此,在didFinishLaunchingWithOptions ,您将创建一个本地viewController实例。

And,it will be dealloced after the method is done. 并且,该方法完成后将被取消分配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM