【问题标题】:add variable in AppDelegate Objective c [closed]在 AppDelegate Objective c 中添加变量 [关闭]
【发布时间】:2014-12-27 14:12:53
【问题描述】:

我正在尝试在我的 appDelegate 中添加两个变量,以便我可以在其他视图控制器中使用它们。

我的代码如下所示:

myappdelegate.h:

@class MyViewController1, MyViewController2; // controller than use my new variables

@interface AppDelegate : UIResponder <UIApplicationDelegate>
{
    NSString* firstVariable; 
    NSString* secondVariable; 
}
@property (retain) NSString* firstVariable;
@property (retain) NSString* secondVariable;

@end

在 myappdelegate.m 中我合成了变量:

...
@synthesize firstVariable = _firstVariable;
@synthesize secondVariable = _secondVariable;
...

但是当在我的视图控制器中使用 myappdelegate 时找不到我的新变量:

...
mainDelegate = (AppDelegate *)[[UIApplication sharedApplication]delegate];
...
mainDelegate.firstVariable = localVariable.text;
...

我的错误在哪里??

谢谢大家。

【问题讨论】:

  • 有很多错误。一个主要的问题是实例变量的名称与合成属性时使用的名称不同。此外,除非您的委托访问这些控制器,否则您不需要 @class 行。您的视图控制器是否导入“AppDelegate.h”?你如何声明mainDelegate
  • 啊!使用应用程序委托在您的视图控制器之间传递数据!你不妨在额头上纹一个牌子,上面写着“我不知道自己在做什么”。
  • 那么,有错误信息吗?
  • 您可能需要将 AppDelegate.h 文件导入到您的其他类中。
  • 是的,我将 AppDelegate.h 导入到我的其他类中,但没有找到!

标签: ios objective-c xcode variables appdelegate


【解决方案1】:

摆脱你的实例变量和@synthesize 语句。编译器将为您完成这项工作。

确保你#import AppDelegate.h每个你需要它的地方,特别是在 MyViewController1.m 和 MyViewController2.m。

我的猜测是您没有在视图控制器的 .m 文件中导入 AppDelegate.h 文件。

正如@Abizern 所说,使用应用程序委托来传递数据并不是一个好的设计模式。你应该让你的应用代理简单,只响应代理消息和通知。

最好创建一个数据容器单例并使用它在项目中的对象之间共享数据。

【讨论】:

  • 我确定我在两个 viewController 中都导入了 appDelegate。我使用我的 appdelegate 设置两种状态.. 不传递数据.. 插入数据时需要设置一种状态...
  • 状态是一种数据形式。
  • 是的,我创建了一个类,我在其他类中更改。现在我找到了我所有的礼仪,并在我的所有职能中改变了它们。谢谢邓肯
【解决方案2】:
Code:
@interface AppDelegate : UIResponder <UIApplicationDelegate>
{
    NSString* firstVariable;
    NSString* secondVariable;
}
@property (retain) NSString* firstVariable;
@property (retain) NSString* secondVariable;


@implementation AppDelegate

@synthesize firstVariable;
@synthesize secondVariable;


Inside your View Controller :

#import "AppDelegate.h"

@interface ViewController : UIViewController{
AppDelegate *mainDelegate;
}

#import "AppDelegate.h"

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    mainDelegate = (AppDelegate *)[[UIApplication sharedApplication]delegate];
    NSLog(@"Vars are :%@ , %@",mainDelegate.firstVariable,mainDelegate.secondVariable);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-08
    • 1970-01-01
    • 2013-03-22
    • 2012-08-27
    • 1970-01-01
    相关资源
    最近更新 更多