如何在 ViewController 中使用 appDelegate 中声明的字符串?

发布于 2024-12-18 21:26:52 字数 99 浏览 1 评论 0原文

假设我已经在 appDelegate 中声明了 NSString 并且我想在我的 ViewController 中使用该字符串。我如何在 ViewController 中使用该字符串?

Suppose i have declared the NSString in appDelegate and i want to use that string in my ViewController. How can i use that string in my ViewController?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

为你鎻心 2024-12-25 21:26:52

对于只是一个字符串,很多人会推荐 NSUserDefaults。

如果您想使用 AppDelegate,答案与此问题重叠 Call a function in AppDelegate?

这是我的答案

您可以创建一个头文件,其中包含 AppDelegate 的宏

GlobalData.h

#import "AppDelegate.h"
#define APPDELEGATE (AppDelegate *)[[UIApplication sharedApplication] delegate]

然后在任何类中使用它

#import "GlobalData.h"

// to gain access to the delegate
AppDelegate * appDelegate = APPDELEGATE;

要访问您的字符串(假设它是一个名为 globalString 的属性)

appDelegate.globalString;

我使用这种方法,因为我可以存储更多#define 一些全局常量
(即 soundFXVolume - #define SOUND_FX_V 0.6

For just a string, many people will recommend NSUserDefaults.

If you want to use the AppDelegate, the answer overlaps this question Call a function in AppDelegate?

Here is my answer

You can create a header file that has a macro to the AppDelegate

GlobalData.h

#import "AppDelegate.h"
#define APPDELEGATE (AppDelegate *)[[UIApplication sharedApplication] delegate]

Then use it in any class

#import "GlobalData.h"

// to gain access to the delegate
AppDelegate * appDelegate = APPDELEGATE;

To access your string (assume it is a property called globalString)

appDelegate.globalString;

I use this approach because I can then store more #define's to some global constants
(ie soundFXVolume - #define SOUND_FX_V 0.6)

Hello爱情风 2024-12-25 21:26:52
((appDelegate *)[UIApplication sharedApplication].delegate).myString;
((appDelegate *)[UIApplication sharedApplication].delegate).myString;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文