引用AppDelegate方法 - iphone

jal*_*alo 15 iphone xcode

我有一个AppDelegate有3个视图.我加上三个

[window addSubview:gameViewController.view];
[window addSubview:viewSettings.view];
[window addSubview:viewController.view];
[window makeKeyAndVisible];
Run Code Online (Sandbox Code Playgroud)

在app委托中,我有一些通过调用来交换视图的方法

[window bringSubviewToFront:gameViewController.view]; 
Run Code Online (Sandbox Code Playgroud)

当我在viewController中时,我使用

pinkAppDelegate *appDelegate=  (pinkAppDelegate *)[[UIApplication sharedApplication] delegate];

[appDelegate switchToSettings];
Run Code Online (Sandbox Code Playgroud)

切换我的子视图......到目前为止一切顺利.

但是,当我在我的viewSetting UIViewController中,并执行相同的appDelegate调用时,它会窒息,就像它不知道如何调用appDelegate方法一样.

我的所有视图都挂在我的mainwindow xib中,但无法弄清楚为什么我无法遍历主appdelegate中的方法

Jan*_*les 28

在viewController中,您正在设置一个名为appDelegate的局部变量,该变量指向您的应用委托.这就是这条线的作用:

pinkAppDelegate *appDelegate= (pinkAppDelegate *)[[UIApplication sharedApplication] delegate];
Run Code Online (Sandbox Code Playgroud)

此变量是viewController的本地变量,因此您无法在设置视图控制器中使用它.你需要在那里设置另一个变量.

或者,在整个应用中使用这个漂亮的#define.(您需要将它放在项目中每个文件中包含的.h头文件中.)

#define myAppDelegate (MyAppDelegate *)[[UIApplication sharedApplication] delegate]
Run Code Online (Sandbox Code Playgroud)

然后你可以在任何地方做以下事情:

[myAppDelegate doSomething];
Run Code Online (Sandbox Code Playgroud)

  • #define版本似乎对我不起作用.我收到警告"UIApplication可能无法响应+ sharedApplication"这样的错误,并且在启动后无法正常工作...有什么建议吗?谢谢 (5认同)

ago*_*ugh 10

作为参考,上面还有一个拼写错误,我还有另外一个补充,这有助于避免每次都必须施放警告.如果您使用:

#import "MyAppDelegate.h"
#define myAppDelegate (MyAppDelegate *) [[UIApplication sharedApplication] delegate]
Run Code Online (Sandbox Code Playgroud)

我把上面的内容放在constants.h然后就可以使用了

[myAppDelegate doSomething];
Run Code Online (Sandbox Code Playgroud)

我导入constants.h的任何地方