我认为您已经混淆了委托与其视图控制器之间的关系。AppDelegate 在您启动应用程序时创建。您无需在 Forum.h 中创建 AppDelegate,而是在 AppDelegate 中创建 ViewController、Forum。大括号中的 *globalUserName 也是不必要的。
所以 AppDelegate.h 会这样写:
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@property (nonatomic, retain) NSMutableString *globalUsername;
@property (nonatomic, retain) Forum *forum;
此外,在当前版本的 Xcode 和 Objective-C 中,也不需要综合。它会自动设置和初始化。在 AppDelegate.m 中,您可以使用以下命令引用 *globalUsername:
self.globalUsername
您的 AppDelegate.m 还应在 applicationDidLaunch 中包含以下内容:
[[self.forum alloc] init]; //Allocate and initialize the forum ViewController
self.forum.delegate = self; //Set the forum ViewController's delegate variable to be the AppDelegate itself
但是 Forum ViewController 目前没有一个名为 delegate 的变量,所以我们必须创建它。所以在 Forum.h 你应该添加:
@property (nonatomic) id delegate;
所以现在在 Forum.m 中,由于 AppDelegate.m 负责设置委托,我们现在可以使用论坛的委托变量引用 AppDelegate 中的数据。
所以最后,为了从 Forum.m 访问 globalUsername,我们可以使用 self.delegate.globalUsername。因此,要附加到来自 Forum.m 的字符串,我们可以使用:
[self.delegate.globalUsername appendString:myNewString];
其中“myNewString”是要添加到 globalUsername 的字符串。
希望这可以帮助。