开发者

How to access app delegate fields within other classes?

in one of my controllers I want to access fields of my app delegate. So to retrieve app delegate I use the following code:

[[UIApplication sharedApplic开发者_C百科ation] delegate];

But when I try to cast it to my delegate's name I get the error that the name is undeclared.

Do I have to import the header file of the app delegate in the class where I want to access the fields?


you have to provide header file(MyAppDelegate.h) for app delegate.you can access appdelegate members as following.please see the link

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


Do I have to import the header file of the app delegate in the class where I want to access the fields?

Yes. You could also toss the #import statement in the precompiled header (.pch) file. That will give you a reference to the specific class from all files in your project.

Alternatively, you could always play the dangerous game of ignoring the compiler "may not respond" warnings and just send messages without the cast to your specific class. (Treat it as an id.)


first import appdelegate class in your viewController class like

In your ViewController.m file

# import "SampleAppDelegate.h" *write yours*

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

After that you can access fields of appDelegate eg.

[appDelegate.nameArray count];

nameArray is my array declared in appDelegate.


in swift you should use UIApplication.shared.delegate as! AppDelegate

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜