简体   繁体   English

如何从RootViewController调用AppDelegate方法而不传递委托?

[英]how to call an AppDelegate method from RootViewController without passing a delegate?

how to call an AppDelegate method from RootViewController without passing a delegate? 如何从RootViewController调用AppDelegate方法而不传递委托?

Just wondering whether there is a way to do this? 只是想知道是否有办法做到这一点? (or do I need to create a delegate object in the RootViewController to hold a reference to the AppDelegate) (或者我是否需要在RootViewController中创建一个委托对象来保存对AppDelegate的引用)

[[[UIApplication sharedApplication] delegate] someMethod];

奇迹般有效!

您可以使用以下任何方式从任何控制器访问应用程序委托:

MyDelegate* aDelegate = (MyDelegate *)[[UIApplication sharedApplication] delegate];

This happens so frequently, that I always add a method to MyCustomAppDelegate to do this for me (so I don't have a lot of casting in my code. 这种情况经常发生,以至于我总是向MyCustomAppDelegate添加方法来为我执行此操作(因此,我的代码中没有很多强制转换。

@implementation MyCustomAppDelegate ()
- (MyCustomAppDelegate *)appDelegate {
  return (MyCustomAppDelegate *)[[UIApplication sharedApplication] delegate];
}
@end

now anywhere i can call 现在我可以打电话给任何地方

[MyCustomAppDelgate appDelegate]

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

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