【问题标题】:How to make variable accessible in the appDelegate and/or other view controllers?如何在 appDelegate 和/或其他视图控制器中使变量可访问?
【发布时间】:2012-08-30 15:13:01
【问题描述】:

我有一个布尔变量,我需要在我的 appDelegate 中访问它,但我不知道该怎么做。我试图导入另一个视图控制器然后实现它,但它出现了一个 Apple Mach-O 链接器 (id) 错误,显示“链接器命令失败,退出代码为 1”。我对应用程序开发相当陌生,所以请用简单的术语解释一下。我正在使用情节提要,因此无法将 xib/nib 文件与我的代码结合使用。

【问题讨论】:

    标签: objective-c xcode uiviewcontroller global-variables


    【解决方案1】:

    你可以在你的 MyAppDelegate.h 中声明一个属性:

    @property (strong, nonatomic) NSString *myString;
    

    然后你可以在你的 ViewController 中访问它:

    #import "MyAppDelegate.h"
    ...
    MyAppDelegate *appDelegate = (MyAppDelegate *)[[UIApplication sharedApplication] delegate];
    NSLog(@"%@", appDelegate.myString);
    

    【讨论】:

    • 谢谢,这正是我想要的。我将根据 bool 的状态更改字符串。
    • 你可以像这样声明BOOL属性:@property (nonatomic, assign) BOOL myBoolProperty;
    【解决方案2】:

    将 AppDelegate.h 中声明的 Bool 变量访问到任何其他 UIViewController..

    1) 在 AppDelegate.h

    @property (nonatomic)BOOL myBool;
    

    2) 在 AppDelegate.m

    @synthesize myBool;
    

    3) 访问任何其他 UIViewController 中的 myBool 变量

    #define myAppDelegate [[UIApplication sharedApplication]delegate]
    
    // define above line below @implementation XyzViewController
    
     if (((AppDelegate *)myAppDelegate).myBool)
     {
        //implement logic    
     }
     else
     {
    
     }
    

    【讨论】:

      猜你喜欢
      • 2012-06-12
      • 1970-01-01
      • 1970-01-01
      • 2012-03-30
      • 2015-09-08
      • 1970-01-01
      • 2018-12-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多