iphone - 使用 AppDelegate 使变量对整个应用程序可用

标签 iphone ios objective-c c xcode

我对使用应用程序委托(delegate)使变量能够在我的应用程序中的任何位置设置和使用的概念感到非常困惑。这是我的代码:

应用委托(delegate).h

@interface AppDelegate : UIResponder <UIApplicationDelegate>
{
    NSMutableString *globalUsername;
}
@property (strong, nonatomic) UIWindow *window;
@property (nonatomic, retain) NSMutableString *globalUsername;

appdelegate.m

@synthesize globalUsername;

和另一个 View 场景(称为“Forum.h”,我试图在其中设置值)

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

最后一行当然是不完整的,但是 xcode 自动选择了 globalUsername 变量,我只是不能调用“appendString”函数来实际改变它。

最佳答案

呃,如果你想存储用户名,为什么不直接使用 NSUserDefaults 呢?

// set the username
[[NSUserDefaults standardUserDefaults] setValue:@"johnsmith" forKey:@"username"];
[[NSUserDefaults standardUserDefaults] synchronize];

// retrieve the user name
NSString *username = [[NSUserDefaults standardUserDefaults] valueForKey:@"username"];

关于iphone - 使用 AppDelegate 使变量对整个应用程序可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14291244/

相关文章:

ios - 如何使用 ALAsset 保存和重新加载图像?

ios - Swift:构建还是不构建

ios - UITableView 需要双击 - 但不是第一次

ios - UILabel 圆角在 iOS 7.1 中变得尖锐

ios - Restkit 简单的 NSDictionary 映射

Objective C 中的 C++ 数组给出 EXC_BAD_ACCESS

iphone - 有什么方法可以将此 map 转换为在 UIMapView 中工作吗?

iphone - 如何在 iPhone 应用程序上远程访问实时网络摄像头?

html - 视差图像模糊/V。在 iphone 上像素化。需要 CSS 提示

ios - UIViewController 初始加载时高度错误