2014-12-27 198 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); 
}