2014-12-27 190 views
-2

我想在我的appDelegate中添加两个变量,以便我可以在其他视图控制器中使用它们。在AppDelegate中添加变量Objective c

我的代码如下所示:

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; 
... 

但是当我的ViewController使用myappdelegate不要”找到我的新变量:

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

我的错误在哪里?

感谢所有。

+1

有一些错误。主要的一点是,实例变量的名称与合成属性时使用的名称不同。另外,除非委托人访问这些控制器,否则不需要'@ class'行。你的视图控制器是否导入“AppDelegate.h”?你如何声明'mainDelegate'? – 2014-12-27 14:28:22

+2

啊!使用应用程序委托在您的视图控制器之间传递数据!你可能还会在额头上贴上一句“我不知道自己在做什么”的标志。 – Abizern 2014-12-27 14:30:05

+0

那么,有没有错误信息? – 2014-12-27 14:32:33

回答

1

摆脱您的实例变量和@synthesize语句。编译器会为你做这个工作。

确保你每个地方都需要它,尤其是在MyViewController1.m和MyViewController2.m中。

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

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

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

+0

我确定我在我的viewController中导入了我的appDelegate。我使用我的appdelegate设置两个状态..不通过数据..我需要设置一个状态,当我插入数据... – Psycho80 2014-12-27 15:58:23

+0

状态是一种数据形式。 – 2014-12-28 15:15:17

+0

是的,我创建了一个课程,其中我修改了其他课程。现在我发现我所有的礼节,并且在我的所有功能中改变它们。谢谢邓肯 – Psycho80 2014-12-29 14:38:11

0
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); 
}